Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[dotnet] Modernize exception handling in tests #14776

Merged
merged 16 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dotnet/src/webdriver/WebDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -935,7 +935,7 @@ private static object ConvertObjectToJavaScriptObject(object arg)
}
else
{
throw new ArgumentException("Argument is of an illegal type" + arg.ToString(), nameof(arg));
throw new ArgumentException("Argument is of an illegal type: " + arg.ToString(), nameof(arg));
nvborisenko marked this conversation as resolved.
Show resolved Hide resolved
}

return converted;
Expand Down
95 changes: 43 additions & 52 deletions dotnet/test/common/AlertsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,9 @@ public void ShouldThrowArgumentNullExceptionWhenKeysNull()
IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
Assert.That(() => alert.SendKeys(null), Throws.ArgumentNullException);
Assert.That(
() => alert.SendKeys(null),
Throws.ArgumentNullException);
}
finally
{
Expand Down Expand Up @@ -147,13 +149,12 @@ public void SettingTheValueOfAnAlertThrows()
driver.FindElement(By.Id("alert")).Click();

IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");

try
{
alert.SendKeys("cheese");
Assert.Fail("Expected exception");
}
catch (ElementNotInteractableException)
{
Assert.That(
() => alert.SendKeys("cheese"),
Throws.TypeOf<ElementNotInteractableException>());
}
finally
{
Expand Down Expand Up @@ -198,8 +199,10 @@ public void AlertShouldNotAllowAdditionalCommandsIfDismissed()

IAlert alert = WaitFor<IAlert>(AlertToBePresent, "No alert found");
alert.Dismiss();
string text;
Assert.That(() => text = alert.Text, Throws.InstanceOf<NoAlertPresentException>());

Assert.That(
() => alert.Text,
Throws.TypeOf<NoAlertPresentException>());
}

[Test]
Expand Down Expand Up @@ -249,7 +252,9 @@ public void SwitchingToMissingAlertThrows()
{
driver.Url = CreateAlertPage("cheese");

Assert.That(() => AlertToBePresent(), Throws.InstanceOf<NoAlertPresentException>());
Assert.That(
AlertToBePresent,
RenderMichael marked this conversation as resolved.
Show resolved Hide resolved
Throws.TypeOf<NoAlertPresentException>());
}

[Test]
Expand All @@ -270,15 +275,9 @@ public void SwitchingToMissingAlertInAClosedWindowThrows()
driver.Close();
WaitFor(WindowHandleCountToBe(1), "Window count was not 1");

try
{
AlertToBePresent().Accept();
Assert.Fail("Expected exception");
}
catch (NoSuchWindowException)
{
// Expected
}
Assert.That(
() => AlertToBePresent().Accept(),
Throws.TypeOf<NoSuchWindowException>());

}
finally
Expand Down Expand Up @@ -321,17 +320,22 @@ public void HandlesTwoAlertsFromOneInteraction()
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithScripts(
"function setInnerText(id, value) {",
" document.getElementById(id).innerHTML = '<p>' + value + '</p>';",
"}",
"function displayTwoPrompts() {",
" setInnerText('text1', prompt('First'));",
" setInnerText('text2', prompt('Second'));",
"}")
"""
function setInnerText(id, value) {
document.getElementById(id).innerHTML = '<p>' + value + '</p>';
}

function displayTwoPrompts() {
setInnerText('text1', prompt('First'));
setInnerText('text2', prompt('Second'));
}
""")
.WithBody(
"<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>",
"<div id='text1'></div>",
"<div id='text2'></div>"));
"""
<a href='#' id='double-prompt' onclick='displayTwoPrompts();'>click me</a>
<div id='text1'></div>
<div id='text2'></div>
"""));

driver.FindElement(By.Id("double-prompt")).Click();

Expand All @@ -355,7 +359,7 @@ public void HandlesTwoAlertsFromOneInteraction()
public void ShouldHandleAlertOnPageLoad()
{
string pageWithOnLoad = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithOnLoad("javascript:alert(\"onload\")")
.WithOnLoad("""javascript:alert("onload")""")
.WithBody("<p>Page with onload event handler</p>"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.CreateInlinePage(new InlinePage()
.WithBody(string.Format("<a id='open-page-with-onload-alert' href='{0}'>open new page</a>", pageWithOnLoad)));
Expand Down Expand Up @@ -411,17 +415,12 @@ public void ShouldNotHandleAlertInAnotherWindow()
Assert.AreEqual(1, allWindows.Count);
onloadWindow = allWindows[0];

try
Assert.That(() =>
{
IWebElement el = driver.FindElement(By.Id("open-new-window"));
WaitFor<IAlert>(AlertToBePresent, TimeSpan.FromSeconds(5), "No alert found");
Assert.Fail("Expected exception");
}
catch (WebDriverException)
{
// An operation timed out exception is expected,
// since we're using WaitFor<T>.
}
},
Throws.TypeOf<WebDriverException>());

}
finally
Expand All @@ -442,15 +441,10 @@ public void IncludesAlertTextInUnhandledAlertException()

driver.FindElement(By.Id("alert")).Click();
WaitFor<IAlert>(AlertToBePresent, "No alert found");
try
{
string title = driver.Title;
Assert.Fail("Expected UnhandledAlertException");
}
catch (UnhandledAlertException e)
{
Assert.AreEqual("cheese", e.AlertText);
}

Assert.That(
() => driver.Title,
Throws.TypeOf<UnhandledAlertException>().With.Property(nameof(UnhandledAlertException.AlertText)).EqualTo("cheese"));
}

[Test]
Expand Down Expand Up @@ -522,16 +516,14 @@ private Func<IWebElement> ElementToBePresent(By locator)
{
return () =>
{
IWebElement foundElement = null;
try
{
foundElement = driver.FindElement(By.Id("open-page-with-onunload-alert"));
return driver.FindElement(By.Id("open-page-with-onunload-alert"));
}
catch (NoSuchElementException)
{
return null;
}

return foundElement;
};
}

Expand All @@ -554,9 +546,8 @@ private Func<bool> WindowWithName(string name)
}
catch (NoSuchWindowException)
{
return false;
}

return false;
};
}

Expand Down
16 changes: 4 additions & 12 deletions dotnet/test/common/CorrectEventFiringTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -348,20 +348,12 @@ public void SendingKeysToAFocusedElementShouldNotBlurThatElement()
focused = true;
break;
}
try
{
System.Threading.Thread.Sleep(200);
}
catch (Exception)
{
throw;
}
}
if (!focused)
{
Assert.Fail("Clicking on element didn't focus it in time - can't proceed so failing");

System.Threading.Thread.Sleep(200);
}

Assert.That(focused, Is.True, "Clicking on element didn't focus it in time - can't proceed so failing");

element.SendKeys("a");
AssertEventNotFired("blur");
}
Expand Down
23 changes: 7 additions & 16 deletions dotnet/test/common/ElementAttributeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,28 +127,19 @@ public void ShouldThrowExceptionIfSendingKeysToElementDisabledUsingRandomDisable
{
driver.Url = formsPage;
IWebElement disabledTextElement1 = driver.FindElement(By.Id("disabledTextElement1"));
try

Assert.That(() =>
{
disabledTextElement1.SendKeys("foo");
Assert.Fail("Should have thrown exception");
}
catch (InvalidElementStateException)
{
//Expected
}
}, Throws.TypeOf<ElementNotInteractableException>());

Assert.AreEqual(string.Empty, disabledTextElement1.Text);

IWebElement disabledTextElement2 = driver.FindElement(By.Id("disabledTextElement2"));
try
{
disabledTextElement2.SendKeys("bar");
Assert.Fail("Should have thrown exception");
}
catch (InvalidElementStateException)
{
//Expected
}

Assert.That(
() => disabledTextElement2.SendKeys("bar"),
Throws.TypeOf<ElementNotInteractableException>());

Assert.AreEqual(string.Empty, disabledTextElement2.Text);
}
Expand Down
23 changes: 7 additions & 16 deletions dotnet/test/common/Environment/RemoteSeleniumServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,12 @@ public async Task StartAsync()

while (!isRunning && DateTime.Now < timeout)
{
try
{
using var response = await httpClient.GetAsync("http://localhost:6000/wd/hub/status");
var statusTask = httpClient.GetAsync("http://localhost:6000/wd/hub/status");
await ((Task)statusTask).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);

if (response.StatusCode == HttpStatusCode.OK)
{
isRunning = true;
}
}
catch (Exception ex) when (ex is HttpRequestException || ex is TimeoutException)
if (statusTask.IsCompletedSuccessfully && statusTask.Result.StatusCode == HttpStatusCode.OK)
{
isRunning = true;
}
}

Expand All @@ -91,14 +86,10 @@ public async Task StopAsync()
{
if (autoStart && webserverProcess != null && !webserverProcess.HasExited)
{
using var httpClient = new HttpClient();

try
{
using var response = await httpClient.GetAsync("http://localhost:6000/selenium-server/driver?cmd=shutDownSeleniumServer");
}
catch (Exception ex) when (ex is HttpRequestException || ex is TimeoutException)
using (var httpClient = new HttpClient())
{
await ((Task)httpClient.GetAsync("http://localhost:6000/selenium-server/driver?cmd=shutDownSeleniumServer"))
.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
}

webserverProcess.WaitForExit(10000);
Expand Down
13 changes: 2 additions & 11 deletions dotnet/test/common/Environment/TestWebServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,17 +181,8 @@ public async Task StopAsync()
{
using (var httpClient = new HttpClient())
{
try
{
using (await httpClient.GetAsync(EnvironmentManager.Instance.UrlBuilder.LocalWhereIs("quitquitquit")))
{

}
}
catch (HttpRequestException)
{

}
await ((Task)httpClient.GetAsync(EnvironmentManager.Instance.UrlBuilder.LocalWhereIs("quitquitquit")))
.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
}

try
Expand Down
Loading