I’m using the Microsoft Edge WebDriver to test inprivate browser windows but I’ve noticed 2 things:
- WebDriver process does not always end
- When running more than 1 at a time, taking screenshots often fail once the first web driver has been disposed (the same error is often thrown when calling
driver.Quit()
My core code follows, but is there a better method to instantiate the driver so that it will clean up properly and be more reliable when running?
protected void TestBrowser(string testFilePath, string parameterFile)
{
var ops = TestEnvironment.BrowserOptions;
var prof = ops.Arguments[ops.Arguments.Count-1];
using (var service = TestEnvironment.Service)
{
using (var driver = new EdgeDriver(service, ops))
{
driver.Manage().Timeouts().ImplicitWait = new TimeSpan(0, 0, 10);
driver.Manage().Timeouts().PageLoad = new TimeSpan(0, 2, 0);
driver.Manage().Timeouts().AsynchronousJavaScript = new TimeSpan(0, 0, 10);
try
{
// loop containing Asserts and `driver.FindElements()` etc
}
finally
{
TakeScreenShot(driver: driver);
output.WriteLine($"finally {prof}");
driver?.Quit(); // throws exceptions
After();
}
}
}
}
private void TakeScreenShot(EdgeDriver driver, string? name = null, Exception? ex = null)
{
lock (screenShotLock)
{
var path = $"{TestName}{ScriptFileName}{ParameterFileName}{new Random().Next(10000}.png";
driver.GetScreenshot().SaveAsFile(path); // throws exception
}
}
public static EdgeOptions BrowserOptions
{
get
{
lock (optionsLockObj)
{
ProfileCounter++;
var _options = new EdgeOptions();
_options.LeaveBrowserRunning = false;
_options.AcceptInsecureCertificates = true;
_options.BinaryLocation = @"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe";
if (Directory.Exists($@"{Directory.GetCurrentDirectory()}\prof-{ProfileCounter}"))
Directory.Delete($@"{Directory.GetCurrentDirectory()}\prof-{ProfileCounter}", true);
_options.AddArgument($@"--user-data-dir={Directory.GetCurrentDirectory()}\prof-{ProfileCounter}");
_options.AddArgument($"remote-debugging-port={9222+ProfileCounter}");
_options.SetLoggingPreference(LogType.Driver, LogLevel.Debug);
return _options;
}
}
}
public static EdgeDriverService Service
{
get
{
lock (serviceLockObj)
{
if (_service is null)
{
var _service = EdgeDriverService.CreateDefaultService(@"/driver/", @"msedgedriver.exe");
_service.UseVerboseLogging = true;
_service.Start();
}
}
return _service;
}
}