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 1 commit
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
21 changes: 7 additions & 14 deletions dotnet/test/common/AlertsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -442,15 +442,11 @@ 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.That(() =>
{
Assert.AreEqual("cheese", e.AlertText);
}
_ = driver.Title;
RenderMichael marked this conversation as resolved.
Show resolved Hide resolved
}, Throws.InstanceOf<UnhandledAlertException>().With.Property(nameof(UnhandledAlertException.AlertText)).EqualTo("cheese"));
}

[Test]
Expand Down Expand Up @@ -522,16 +518,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 +548,8 @@ private Func<bool> WindowWithName(string name)
}
catch (NoSuchWindowException)
{
return false;
}

return false;
};
}

Expand Down
7 changes: 2 additions & 5 deletions dotnet/test/common/BiDi/Network/NetworkEventsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,8 @@ public async Task CanListenToFetchError()

await using var subscription = await context.Network.OnFetchErrorAsync(tcs.SetResult);

try
{
await context.NavigateAsync("https://not_a_valid_url.test", new() { Wait = ReadinessState.Complete });
}
catch (Exception) { }
var navigateTask = context.NavigateAsync("https://not_a_valid_url.test", new() { Wait = ReadinessState.Complete });
await ((Task)navigateTask).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);
RenderMichael marked this conversation as resolved.
Show resolved Hide resolved
RenderMichael marked this conversation as resolved.
Show resolved Hide resolved

var res = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5));

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
20 changes: 6 additions & 14 deletions dotnet/test/common/ElementAttributeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,28 +127,20 @@ 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.InstanceOf<InvalidElementStateException>());

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

IWebElement disabledTextElement2 = driver.FindElement(By.Id("disabledTextElement2"));
try

Assert.That(() =>
{
disabledTextElement2.SendKeys("bar");
Assert.Fail("Should have thrown exception");
}
catch (InvalidElementStateException)
{
//Expected
}
}, Throws.InstanceOf<InvalidElementStateException>());

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())
{
var shutDownTask = httpClient.GetAsync("http://localhost:6000/selenium-server/driver?cmd=shutDownSeleniumServer");
await ((Task)shutDownTask).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)
{

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

try
Expand Down
67 changes: 54 additions & 13 deletions dotnet/test/common/ExecutingJavascriptTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -594,26 +594,67 @@ public void ShouldHandleRecursiveStructures()
[Ignore("Reason for ignore: Failure indicates hang condition, which would break the test suite. Really needs a timeout set.")]
public void ShouldThrowExceptionIfExecutingOnNoPage()
{
bool exceptionCaught = false;
try
Assert.That(() =>
{
((IJavaScriptExecutor)driver).ExecuteScript("return 1;");
}
catch (WebDriverException)
{
exceptionCaught = true;
}

if (!exceptionCaught)
{
Assert.Fail("Expected an exception to be caught");
}
}, Throws.InstanceOf<WebDriverException>());
}

[Test]
public void ExecutingLargeJavaScript()
{
string script = "// stolen from injectableSelenium.js in WebDriver\nvar browserbot = {\n\n triggerEvent: function(element, eventType, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown) {\n canBubble = (typeof(canBubble) == undefined) ? true: canBubble;\n if (element.fireEvent && element.ownerDocument && element.ownerDocument.createEventObject) {\n // IE\n var evt = this.createEventObject(element, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown);\n element.fireEvent('on' + eventType,evt);\n } else {\n var evt = document.createEvent('HTMLEvents');\n\n try {\n evt.shiftKey = shiftKeyDown;\n evt.metaKey = metaKeyDown;\n evt.altKey = altKeyDown;\n evt.ctrlKey = controlKeyDown;\n } catch(e) {\n // Nothing sane to do\n }\n\n evt.initEvent(eventType, canBubble, true);\n return element.dispatchEvent(evt);\n }\n },\n\n getVisibleText: function() {\n var selection = getSelection();\n var range = document.createRange();\n range.selectNodeContents(document.documentElement);\n selection.addRange(range);\nvar string = selection.toString();\n selection.removeAllRanges();\n\n return string;\n },\n\n getOuterHTML: function(element) {\n if(element.outerHTML) {\n return element.outerHTML;\n } else if(typeof(XMLSerializer) != undefined) {\n return new XMLSerializer().serializeToString(element);\n } else {\n throw \"can't get outerHTML in this browser\";\n }\n }\n\n\n};return browserbot.getOuterHTML.apply(browserbot, arguments);";
string script = """
RenderMichael marked this conversation as resolved.
Show resolved Hide resolved
// stolen from injectableSelenium.js in WebDriver
var browserbot = {

triggerEvent: function(element, eventType, canBubble, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown) {
canBubble = (typeof(canBubble) == undefined) ? true: canBubble;
if (element.fireEvent && element.ownerDocument && element.ownerDocument.createEventObject) {
// IE
var evt = this.createEventObject(element, controlKeyDown, altKeyDown, shiftKeyDown, metaKeyDown);
element.fireEvent('on' + eventType,evt);
} else {
var evt = document.createEvent('HTMLEvents');

try {
evt.shiftKey = shiftKeyDown;
evt.metaKey = metaKeyDown;
evt.altKey = altKeyDown;
evt.ctrlKey = controlKeyDown;
} catch(e) {
// Nothing sane to do
}

evt.initEvent(eventType, canBubble, true);
return element.dispatchEvent(evt);
}
},

getVisibleText: function() {
var selection = getSelection();
var range = document.createRange();
range.selectNodeContents(document.documentElement);
selection.addRange(range);
var string = selection.toString();
selection.removeAllRanges();

return string;
},

getOuterHTML: function(element) {
if(element.outerHTML) {
return element.outerHTML;
} else if(typeof(XMLSerializer) != undefined) {
return new XMLSerializer().serializeToString(element);
} else {
throw "can't get outerHTML in this browser";
}
}


};return browserbot.getOuterHTML.apply(browserbot, arguments);
""";

driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.TagName("body"));
object x = ExecuteScript(script, element);
Expand Down
27 changes: 7 additions & 20 deletions dotnet/test/common/FrameSwitchingTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,28 +175,18 @@ public void FrameSearchesShouldBeRelativeToTheCurrentlySelectedFrame()
driver.SwitchTo().Frame(frameElement);
Assert.AreEqual("2", driver.FindElement(By.Id("pageNumber")).Text);

try
Assert.That(() =>
{
driver.SwitchTo().Frame("third");
Assert.Fail();
}
catch (NoSuchFrameException)
{
// Do nothing
}
}, Throws.InstanceOf<NoSuchFrameException>());

driver.SwitchTo().DefaultContent();
driver.SwitchTo().Frame("third");

try
Assert.That(() =>
{
driver.SwitchTo().Frame("second");
Assert.Fail();
}
catch (NoSuchFrameException)
{
// Do nothing
}
}, Throws.InstanceOf<NoSuchFrameException>());

driver.SwitchTo().DefaultContent();
driver.SwitchTo().Frame("second");
Expand Down Expand Up @@ -615,9 +605,8 @@ private bool FrameExistsAndSwitchedTo(string locator)
}
catch (NoSuchFrameException)
{
return false;
}

return false;
}

private bool FrameExistsAndSwitchedTo(int index)
Expand All @@ -629,9 +618,8 @@ private bool FrameExistsAndSwitchedTo(int index)
}
catch (NoSuchFrameException)
{
return false;
}

return false;
}

private bool FrameExistsAndSwitchedTo(IWebElement frameElement)
Expand All @@ -643,9 +631,8 @@ private bool FrameExistsAndSwitchedTo(IWebElement frameElement)
}
catch (NoSuchFrameException)
{
return false;
}

return false;
}
}
}
Loading