Reputation: 110
Background: I am using Selenium, C#, and Firefox to automate a task I perform regularly. I have choose this option because the website I am accessing no longer provides a REST API. In my code I regular check for errors such as failing to find a web element. At such time I want my application to gracefully exit with an error message.
For reference my current code
if (driver != null)
{
driver.Quit();
}
Problem: driver.Quit() does not close Firefox or the geckodriver when called from a webpage with a form that has been partially filled out. Instead a dialog will pop up which says
This page is asking you to confirm that you want to leave - data you have entered may not be saved.
Doing some searching I found the dialog is generated by the webpage. I tried looking for a Firefox preference to disable the popup but count not find one that was relevant. One search result turned information about killing the Firefox process.
Question: Is there a recommended Selenium approach for ensuring the Firefox and the web driver are terminated?
Upvotes: 2
Views: 735
Reputation: 547
There are a couple things you can do:
As you mentioned, Process.Kill. An implementation of this I use is:
// ProccessId's can be gotten by Proccess.GetProcessesByName("Name")
public static void KillProcessAndChildren(params int[] processIds)
{
foreach (var processID in processIds)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(
"Select * From Win32_Process Where ParentProcessID=" + processID);
ManagementObjectCollection moc = searcher.Get();
foreach (ManagementObject mo in moc)
{
KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
}
try
{
Process proc = Process.GetProcessById(processID);
proc.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
}
Accept the warning dialog after verifying that you do not need to pay attention to it. This is the best solution in my opinion as it makes sure that if there is an unexpected error, your test does not return a false pass. The code to do this is:
var alert = driver.SwitchTo().Alert();
if (alert.Text == "The expected error message")
alert.Accept();
else
Assert.Fail("The webriver raised an unexpected warning: " + alert.Text);
Upvotes: 1