Skip to content

Commit

Permalink
[dotnet] Modernize exception handling in tests via assert that throws (
Browse files Browse the repository at this point in the history
  • Loading branch information
RenderMichael authored Nov 21, 2024
1 parent 60e3171 commit 0954cca
Show file tree
Hide file tree
Showing 10 changed files with 248 additions and 240 deletions.
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));
}

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(),
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
15 changes: 8 additions & 7 deletions dotnet/test/common/Environment/RemoteSeleniumServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,15 @@ 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())
{
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)
{
}
}

webserverProcess.WaitForExit(10000);
Expand Down
Loading

0 comments on commit 0954cca

Please sign in to comment.