From fa5a0cba1e77942535c5582be71b593270f084a8 Mon Sep 17 00:00:00 2001 From: Michael Render Date: Wed, 2 Apr 2025 00:32:50 -0400 Subject: [PATCH 1/4] [dotnet] Modernize `EnvironmentManager`, standardize assembly teardown --- dotnet/test/chrome/AssemblyTeardown.cs | 41 +++++++++ dotnet/test/chrome/ChromeSpecificTests.cs | 8 -- .../NeedsFreshDriverAttribute.cs | 28 ++---- dotnet/test/common/DriverTestFixture.cs | 23 ++--- .../common/Environment/EnvironmentManager.cs | 86 ++++--------------- dotnet/test/common/StubDriver.cs | 29 ++----- dotnet/test/common/TestUtilities.cs | 11 ++- dotnet/test/edge/AssemblyTeardown.cs | 28 +++--- dotnet/test/firefox/AssemblyTeardown.cs | 28 +++--- .../test/firefox/FirefoxProfileManagerTest.cs | 9 +- dotnet/test/firefox/FirefoxProfileTests.cs | 7 +- dotnet/test/ie/AssemblyTeardown.cs | 28 +++--- dotnet/test/remote/AssemblyTeardown.cs | 37 ++++---- dotnet/test/safari/AssemblyTeardown.cs | 41 +++++++++ 14 files changed, 193 insertions(+), 211 deletions(-) create mode 100644 dotnet/test/chrome/AssemblyTeardown.cs create mode 100644 dotnet/test/safari/AssemblyTeardown.cs diff --git a/dotnet/test/chrome/AssemblyTeardown.cs b/dotnet/test/chrome/AssemblyTeardown.cs new file mode 100644 index 0000000000000..789f8bf6b88d9 --- /dev/null +++ b/dotnet/test/chrome/AssemblyTeardown.cs @@ -0,0 +1,41 @@ +// +// Licensed to the Software Freedom Conservancy (SFC) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The SFC licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +using NUnit.Framework; +using OpenQA.Selenium.Environment; +using System.Threading.Tasks; + +[SetUpFixture] +#pragma warning disable // Outside a namespace to affect the entire assembly +public class AssemblyTeardown +#pragma warning restore +{ + [OneTimeSetUp] + public async Task RunBeforeAnyTestAsync() + { + await EnvironmentManager.Instance.WebServer.StartAsync(); + } + + [OneTimeTearDown] + public async Task RunAfterAnyTestsAsync() + { + EnvironmentManager.Instance.CloseCurrentDriver(); + await EnvironmentManager.Instance.WebServer.StopAsync(); + } +} diff --git a/dotnet/test/chrome/ChromeSpecificTests.cs b/dotnet/test/chrome/ChromeSpecificTests.cs index a0cc07f28ea04..13efbad9c2c29 100644 --- a/dotnet/test/chrome/ChromeSpecificTests.cs +++ b/dotnet/test/chrome/ChromeSpecificTests.cs @@ -18,19 +18,11 @@ // using NUnit.Framework; -using OpenQA.Selenium.Environment; -using System.Threading.Tasks; namespace OpenQA.Selenium.Chrome { [TestFixture] public class ChromeSpecificTests : DriverTestFixture { - [OneTimeTearDown] - public async Task RunAfterAnyTestsAsync() - { - EnvironmentManager.Instance.CloseCurrentDriver(); - await EnvironmentManager.Instance.WebServer.StopAsync(); - } } } diff --git a/dotnet/test/common/CustomTestAttributes/NeedsFreshDriverAttribute.cs b/dotnet/test/common/CustomTestAttributes/NeedsFreshDriverAttribute.cs index 669dd82d01db4..12463644db845 100644 --- a/dotnet/test/common/CustomTestAttributes/NeedsFreshDriverAttribute.cs +++ b/dotnet/test/common/CustomTestAttributes/NeedsFreshDriverAttribute.cs @@ -25,40 +25,30 @@ namespace OpenQA.Selenium { public class NeedsFreshDriverAttribute : TestActionAttribute { - private bool isCreatedBeforeTest = false; - private bool isCreatedAfterTest = false; + public bool IsCreatedBeforeTest { get; set; } = false; - public bool IsCreatedBeforeTest - { - get { return isCreatedBeforeTest; } - set { isCreatedBeforeTest = value; } - } - - public bool IsCreatedAfterTest - { - get { return isCreatedAfterTest; } - set { isCreatedAfterTest = value; } - } + public bool IsCreatedAfterTest { get; set; } = false; public override void BeforeTest(ITest test) { - DriverTestFixture fixtureInstance = test.Fixture as DriverTestFixture; - if (fixtureInstance != null && this.isCreatedBeforeTest) + if (test.Fixture is DriverTestFixture fixtureInstance && this.IsCreatedBeforeTest) { EnvironmentManager.Instance.CreateFreshDriver(); - fixtureInstance.DriverInstance = EnvironmentManager.Instance.GetCurrentDriver(); + fixtureInstance.driver = EnvironmentManager.Instance.GetCurrentDriver(); } + base.BeforeTest(test); } public override void AfterTest(ITest test) { - DriverTestFixture fixtureInstance = test.Fixture as DriverTestFixture; - if (fixtureInstance != null && this.isCreatedAfterTest) + if (test.Fixture is DriverTestFixture fixtureInstance && this.IsCreatedAfterTest) { EnvironmentManager.Instance.CreateFreshDriver(); - fixtureInstance.DriverInstance = EnvironmentManager.Instance.GetCurrentDriver(); + fixtureInstance.driver = EnvironmentManager.Instance.GetCurrentDriver(); } + + base.AfterTest(test); } } } diff --git a/dotnet/test/common/DriverTestFixture.cs b/dotnet/test/common/DriverTestFixture.cs index 2f0eacf218f27..dd2aef6edde4c 100644 --- a/dotnet/test/common/DriverTestFixture.cs +++ b/dotnet/test/common/DriverTestFixture.cs @@ -109,20 +109,15 @@ public abstract class DriverTestFixture public string printPage = EnvironmentManager.Instance.UrlBuilder.WhereIs("printPage.html"); - protected IWebDriver driver; - - public IWebDriver DriverInstance - { - get { return driver; } - set { driver = value; } - } + public IWebDriver driver { get; set; } public bool IsNativeEventsEnabled { get { - IHasCapabilities capabilitiesDriver = driver as IHasCapabilities; - if (capabilitiesDriver != null && capabilitiesDriver.Capabilities.HasCapability(CapabilityType.HasNativeEvents) && (bool)capabilitiesDriver.Capabilities.GetCapability(CapabilityType.HasNativeEvents)) + if (driver is IHasCapabilities capabilitiesDriver && + capabilitiesDriver.Capabilities.HasCapability(CapabilityType.HasNativeEvents) && + (bool)capabilitiesDriver.Capabilities.GetCapability(CapabilityType.HasNativeEvents)) { return true; } @@ -154,12 +149,6 @@ protected void CreateFreshDriver() driver = EnvironmentManager.Instance.CreateFreshDriver(); } - protected bool IsIeDriverTimedOutException(Exception e) - { - // The IE driver may throw a timed out exception - return e.GetType().Name.Contains("TimedOutException"); - } - protected bool WaitFor(Func waitFunction, string timeoutMessage) { return WaitFor(waitFunction, timeoutMessage); @@ -173,7 +162,7 @@ protected T WaitFor(Func waitFunction, string timeoutMessage) protected T WaitFor(Func waitFunction, TimeSpan timeout, string timeoutMessage) { DateTime endTime = DateTime.Now.Add(timeout); - T value = default(T); + T value = default; Exception lastException = null; while (DateTime.Now < endTime) { @@ -207,7 +196,7 @@ protected T WaitFor(Func waitFunction, TimeSpan timeout, string timeoutMes } Assert.Fail("Condition timed out: " + timeoutMessage); - return default(T); + return default; } } } diff --git a/dotnet/test/common/Environment/EnvironmentManager.cs b/dotnet/test/common/Environment/EnvironmentManager.cs index 9c0b53b90c56c..fcdf1c2a58545 100644 --- a/dotnet/test/common/Environment/EnvironmentManager.cs +++ b/dotnet/test/common/Environment/EnvironmentManager.cs @@ -31,14 +31,9 @@ namespace OpenQA.Selenium.Environment public class EnvironmentManager { private static EnvironmentManager instance; - private Type driverType; - private Browser browser; + private readonly Type driverType; private IWebDriver driver; - private UrlBuilder urlBuilder; - private TestWebServer webServer; - private DriverFactory driverFactory; - private RemoteSeleniumServer remoteServer; - private string remoteCapabilities; + private readonly DriverFactory driverFactory; private EnvironmentManager() { @@ -91,10 +86,10 @@ private EnvironmentManager() throw new ArgumentOutOfRangeException($"Unable to find driver type {driverConfig.DriverTypeName}"); } - browser = driverConfig.BrowserValue; - remoteCapabilities = driverConfig.RemoteCapabilities; + Browser = driverConfig.BrowserValue; + RemoteCapabilities = driverConfig.RemoteCapabilities; - urlBuilder = new UrlBuilder(websiteConfig); + UrlBuilder = new UrlBuilder(websiteConfig); // When run using the `bazel test` command, the following environment // variable will be set. If not set, we're running from a build system @@ -185,48 +180,28 @@ private EnvironmentManager() // Use the default one. } - webServer = new TestWebServer(projectRoot, webServerConfig); + WebServer = new TestWebServer(projectRoot, webServerConfig); bool autoStartRemoteServer = false; - if (browser == Browser.Remote) + if (Browser == Browser.Remote) { autoStartRemoteServer = driverConfig.AutoStartRemoteServer; } - remoteServer = new RemoteSeleniumServer(projectRoot, autoStartRemoteServer); + RemoteServer = new RemoteSeleniumServer(projectRoot, autoStartRemoteServer); } ~EnvironmentManager() { - if (remoteServer != null) - { - remoteServer.StopAsync().Wait(); - } - if (webServer != null) - { - webServer.StopAsync().Wait(); - } + RemoteServer?.StopAsync().Wait(); + WebServer?.StopAsync().Wait(); CloseCurrentDriver(); } public event EventHandler DriverStarting; - public static EnvironmentManager Instance - { - get - { - if (instance == null) - { - instance = new EnvironmentManager(); - } - - return instance; - } - } + public static EnvironmentManager Instance => instance ??= new EnvironmentManager(); - public Browser Browser - { - get { return browser; } - } + public Browser Browser { get; } public string CurrentDirectory { @@ -242,39 +217,17 @@ public string CurrentDirectory } } - public TestWebServer WebServer - { - get { return webServer; } - } + public TestWebServer WebServer { get; } - public RemoteSeleniumServer RemoteServer - { - get { return remoteServer; } - } + public RemoteSeleniumServer RemoteServer { get; } - public string RemoteCapabilities - { - get { return remoteCapabilities; } - } + public string RemoteCapabilities { get; } - public UrlBuilder UrlBuilder - { - get - { - return urlBuilder; - } - } + public UrlBuilder UrlBuilder { get; } public IWebDriver GetCurrentDriver() { - if (driver != null) - { - return driver; - } - else - { - return CreateFreshDriver(); - } + return driver ?? CreateFreshDriver(); } public IWebDriver CreateDriverInstance() @@ -296,10 +249,7 @@ public IWebDriver CreateFreshDriver() public void CloseCurrentDriver() { - if (driver != null) - { - driver.Quit(); - } + driver?.Quit(); driver = null; } diff --git a/dotnet/test/common/StubDriver.cs b/dotnet/test/common/StubDriver.cs index 3b1ccd5dc72ca..c5c033c1a7dca 100644 --- a/dotnet/test/common/StubDriver.cs +++ b/dotnet/test/common/StubDriver.cs @@ -28,34 +28,19 @@ public class StubDriver : IWebDriver public string Url { - get - { - throw new NotImplementedException(); - } + get => throw new NotImplementedException(); set { } } - public string Title - { - get { throw new NotImplementedException(); } - } + public string Title => throw new NotImplementedException(); - public string PageSource - { - get { throw new NotImplementedException(); } - } + public string PageSource => throw new NotImplementedException(); - public string CurrentWindowHandle - { - get { throw new NotImplementedException(); } - } + public string CurrentWindowHandle => throw new NotImplementedException(); - public ReadOnlyCollection WindowHandles - { - get { throw new NotImplementedException(); } - } + public ReadOnlyCollection WindowHandles => throw new NotImplementedException(); public void Close() { @@ -82,7 +67,7 @@ public ITargetLocator SwitchTo() throw new NotImplementedException(); } - public System.Collections.ObjectModel.ReadOnlyCollection GetWindowHandles() + public ReadOnlyCollection GetWindowHandles() { throw new NotImplementedException(); } @@ -101,7 +86,7 @@ public IWebElement FindElement(By by) throw new NotImplementedException(); } - public System.Collections.ObjectModel.ReadOnlyCollection FindElements(By by) + public ReadOnlyCollection FindElements(By by) { throw new NotImplementedException(); } diff --git a/dotnet/test/common/TestUtilities.cs b/dotnet/test/common/TestUtilities.cs index 73a2a53470b07..15fd969bdb233 100644 --- a/dotnet/test/common/TestUtilities.cs +++ b/dotnet/test/common/TestUtilities.cs @@ -25,7 +25,7 @@ public class TestUtilities { private static IJavaScriptExecutor GetExecutor(IWebDriver driver) { - return driver as IJavaScriptExecutor; + return (IJavaScriptExecutor)driver; } private static string GetUserAgent(IWebDriver driver) @@ -106,13 +106,12 @@ public static bool IsOldIE(IWebDriver driver) public static bool IsNativeEventsEnabled(IWebDriver driver) { - IHasCapabilities hasCaps = driver as IHasCapabilities; - if (hasCaps != null) + if (driver is IHasCapabilities hasCaps) { - object cap = hasCaps.Capabilities.GetCapability(OpenQA.Selenium.CapabilityType.HasNativeEvents); - if (cap != null && cap is bool) + object cap = hasCaps.Capabilities.GetCapability(CapabilityType.HasNativeEvents); + if (cap != null && cap is bool b) { - return (bool)cap; + return b; } } diff --git a/dotnet/test/edge/AssemblyTeardown.cs b/dotnet/test/edge/AssemblyTeardown.cs index ff9875f8f9c00..789f8bf6b88d9 100644 --- a/dotnet/test/edge/AssemblyTeardown.cs +++ b/dotnet/test/edge/AssemblyTeardown.cs @@ -21,23 +21,21 @@ using OpenQA.Selenium.Environment; using System.Threading.Tasks; -namespace OpenQA.Selenium.Edge +[SetUpFixture] +#pragma warning disable // Outside a namespace to affect the entire assembly +public class AssemblyTeardown +#pragma warning restore { - [SetUpFixture] - // Outside a namespace to affect the entire assembly - public class MySetUpClass + [OneTimeSetUp] + public async Task RunBeforeAnyTestAsync() { - [OneTimeSetUp] - public async Task RunBeforeAnyTestAsync() - { - await EnvironmentManager.Instance.WebServer.StartAsync(); - } + await EnvironmentManager.Instance.WebServer.StartAsync(); + } - [OneTimeTearDown] - public async Task RunAfterAnyTestsAsync() - { - EnvironmentManager.Instance.CloseCurrentDriver(); - await EnvironmentManager.Instance.WebServer.StopAsync(); - } + [OneTimeTearDown] + public async Task RunAfterAnyTestsAsync() + { + EnvironmentManager.Instance.CloseCurrentDriver(); + await EnvironmentManager.Instance.WebServer.StopAsync(); } } diff --git a/dotnet/test/firefox/AssemblyTeardown.cs b/dotnet/test/firefox/AssemblyTeardown.cs index a0423752a63f5..789f8bf6b88d9 100644 --- a/dotnet/test/firefox/AssemblyTeardown.cs +++ b/dotnet/test/firefox/AssemblyTeardown.cs @@ -21,23 +21,21 @@ using OpenQA.Selenium.Environment; using System.Threading.Tasks; -namespace OpenQA.Selenium.Firefox +[SetUpFixture] +#pragma warning disable // Outside a namespace to affect the entire assembly +public class AssemblyTeardown +#pragma warning restore { - [SetUpFixture] - // Outside a namespace to affect the entire assembly - public class MySetUpClass + [OneTimeSetUp] + public async Task RunBeforeAnyTestAsync() { - [OneTimeSetUp] - public async Task RunBeforeAnyTestAsync() - { - await EnvironmentManager.Instance.WebServer.StartAsync(); - } + await EnvironmentManager.Instance.WebServer.StartAsync(); + } - [OneTimeTearDown] - public async Task RunAfterAnyTestsAsync() - { - EnvironmentManager.Instance.CloseCurrentDriver(); - await EnvironmentManager.Instance.WebServer.StopAsync(); - } + [OneTimeTearDown] + public async Task RunAfterAnyTestsAsync() + { + EnvironmentManager.Instance.CloseCurrentDriver(); + await EnvironmentManager.Instance.WebServer.StopAsync(); } } diff --git a/dotnet/test/firefox/FirefoxProfileManagerTest.cs b/dotnet/test/firefox/FirefoxProfileManagerTest.cs index 649241074440f..134ca6a24e545 100644 --- a/dotnet/test/firefox/FirefoxProfileManagerTest.cs +++ b/dotnet/test/firefox/FirefoxProfileManagerTest.cs @@ -21,6 +21,7 @@ namespace OpenQA.Selenium.Firefox { + [Ignore("")] [TestFixture] public class FirefoxProfileManagerTest { @@ -32,28 +33,28 @@ public void SetUp() manager = new FirefoxProfileManager(); } - //[Test] + [Test] public void ShouldGetNamedProfile() { FirefoxProfile profile = manager.GetProfile("default"); Assert.That(profile, Is.Not.Null); } - //[Test] + [Test] public void ShouldReturnNullForInvalidProfileName() { FirefoxProfile profile = manager.GetProfile("ThisIsMyBogusProfileName"); Assert.That(profile, Is.Null); } - //[Test] + [Test] public void ShouldReturnNullForNullProfileName() { FirefoxProfile profile = manager.GetProfile(null); Assert.That(profile, Is.Null); } - //[Test] + [Test] public void ShouldReturnNullForEmptyProfileName() { FirefoxProfile profile = manager.GetProfile(string.Empty); diff --git a/dotnet/test/firefox/FirefoxProfileTests.cs b/dotnet/test/firefox/FirefoxProfileTests.cs index 3b1b89cdbd5b8..331b19a17a69e 100644 --- a/dotnet/test/firefox/FirefoxProfileTests.cs +++ b/dotnet/test/firefox/FirefoxProfileTests.cs @@ -22,6 +22,7 @@ namespace OpenQA.Selenium.Firefox { + [Ignore("")] [TestFixture] public class FirefoxProfileTests { @@ -39,7 +40,7 @@ public void TearDown() profile.Clean(); } - //[Test] + [Test] public void ShouldQuoteStringsWhenSettingStringProperties() { profile.SetPreference("cheese", "brie"); @@ -57,7 +58,7 @@ public void ShouldQuoteStringsWhenSettingStringProperties() Assert.That(seenCheese, Is.True); } - //[Test] + [Test] public void ShouldSetIntegerPreferences() { profile.SetPreference("cheese", 1234); @@ -75,7 +76,7 @@ public void ShouldSetIntegerPreferences() Assert.That(seenCheese, Is.True, "Did not see integer value being set correctly"); } - //[Test] + [Test] public void testShouldSetBooleanPreferences() { profile.SetPreference("cheese", false); diff --git a/dotnet/test/ie/AssemblyTeardown.cs b/dotnet/test/ie/AssemblyTeardown.cs index d720502b6e112..789f8bf6b88d9 100644 --- a/dotnet/test/ie/AssemblyTeardown.cs +++ b/dotnet/test/ie/AssemblyTeardown.cs @@ -21,23 +21,21 @@ using OpenQA.Selenium.Environment; using System.Threading.Tasks; -namespace OpenQA.Selenium.IE +[SetUpFixture] +#pragma warning disable // Outside a namespace to affect the entire assembly +public class AssemblyTeardown +#pragma warning restore { - [SetUpFixture] - // Outside a namespace to affect the entire assembly - public class MySetUpClass + [OneTimeSetUp] + public async Task RunBeforeAnyTestAsync() { - [OneTimeSetUp] - public async Task RunBeforeAnyTestAsync() - { - await EnvironmentManager.Instance.WebServer.StartAsync(); - } + await EnvironmentManager.Instance.WebServer.StartAsync(); + } - [OneTimeTearDown] - public async Task RunAfterAnyTestsAsync() - { - EnvironmentManager.Instance.CloseCurrentDriver(); - await EnvironmentManager.Instance.WebServer.StopAsync(); - } + [OneTimeTearDown] + public async Task RunAfterAnyTestsAsync() + { + EnvironmentManager.Instance.CloseCurrentDriver(); + await EnvironmentManager.Instance.WebServer.StopAsync(); } } diff --git a/dotnet/test/remote/AssemblyTeardown.cs b/dotnet/test/remote/AssemblyTeardown.cs index aca281e6ee801..7fb79bc71b978 100644 --- a/dotnet/test/remote/AssemblyTeardown.cs +++ b/dotnet/test/remote/AssemblyTeardown.cs @@ -18,34 +18,33 @@ // using NUnit.Framework; +using OpenQA.Selenium; using OpenQA.Selenium.Environment; using System.Threading.Tasks; -namespace OpenQA.Selenium.Remote +[SetUpFixture] +#pragma warning disable // Outside a namespace to affect the entire assembly +public class AssemblyTeardown +#pragma warning restore { - [SetUpFixture] - // Outside a namespace to affect the entire assembly - public class MySetUpClass + [OneTimeSetUp] + public async Task RunBeforeAnyTestAsync() { - [OneTimeSetUp] - public async Task RunBeforeAnyTestAsync() + await EnvironmentManager.Instance.WebServer.StartAsync(); + if (EnvironmentManager.Instance.Browser == Browser.Remote) { - await EnvironmentManager.Instance.WebServer.StartAsync(); - if (EnvironmentManager.Instance.Browser == Browser.Remote) - { - await EnvironmentManager.Instance.RemoteServer.StartAsync(); - } + await EnvironmentManager.Instance.RemoteServer.StartAsync(); } + } - [OneTimeTearDown] - public async Task RunAfterAnyTestsAsync() + [OneTimeTearDown] + public async Task RunAfterAnyTestsAsync() + { + EnvironmentManager.Instance.CloseCurrentDriver(); + await EnvironmentManager.Instance.WebServer.StopAsync(); + if (EnvironmentManager.Instance.Browser == Browser.Remote) { - EnvironmentManager.Instance.CloseCurrentDriver(); - await EnvironmentManager.Instance.WebServer.StopAsync(); - if (EnvironmentManager.Instance.Browser == Browser.Remote) - { - await EnvironmentManager.Instance.RemoteServer.StopAsync(); - } + await EnvironmentManager.Instance.RemoteServer.StopAsync(); } } } diff --git a/dotnet/test/safari/AssemblyTeardown.cs b/dotnet/test/safari/AssemblyTeardown.cs new file mode 100644 index 0000000000000..789f8bf6b88d9 --- /dev/null +++ b/dotnet/test/safari/AssemblyTeardown.cs @@ -0,0 +1,41 @@ +// +// Licensed to the Software Freedom Conservancy (SFC) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The SFC licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +using NUnit.Framework; +using OpenQA.Selenium.Environment; +using System.Threading.Tasks; + +[SetUpFixture] +#pragma warning disable // Outside a namespace to affect the entire assembly +public class AssemblyTeardown +#pragma warning restore +{ + [OneTimeSetUp] + public async Task RunBeforeAnyTestAsync() + { + await EnvironmentManager.Instance.WebServer.StartAsync(); + } + + [OneTimeTearDown] + public async Task RunAfterAnyTestsAsync() + { + EnvironmentManager.Instance.CloseCurrentDriver(); + await EnvironmentManager.Instance.WebServer.StopAsync(); + } +} From ee41e9a7296e738141cf925adcba24b4a740f1f3 Mon Sep 17 00:00:00 2001 From: Michael Render Date: Mon, 19 May 2025 11:52:04 -0400 Subject: [PATCH 2/4] fix whitespace --- .../common/Environment/EnvironmentManager.cs | 272 +++++++++--------- 1 file changed, 136 insertions(+), 136 deletions(-) diff --git a/dotnet/test/common/Environment/EnvironmentManager.cs b/dotnet/test/common/Environment/EnvironmentManager.cs index 3b4397271edf3..47d648d1e4eb8 100644 --- a/dotnet/test/common/Environment/EnvironmentManager.cs +++ b/dotnet/test/common/Environment/EnvironmentManager.cs @@ -35,151 +35,151 @@ public class EnvironmentManager private IWebDriver driver; private readonly DriverFactory driverFactory; -private EnvironmentManager() -{ - string dataFilePath; - Runfiles runfiles = null; - try - { - runfiles = Runfiles.Create(); - dataFilePath = runfiles.Rlocation("_main/dotnet/test/common/appconfig.json"); - } - catch (FileNotFoundException) + private EnvironmentManager() { - dataFilePath = "appconfig.json"; - } - string currentDirectory = this.CurrentDirectory; + string dataFilePath; + Runfiles runfiles = null; + try + { + runfiles = Runfiles.Create(); + dataFilePath = runfiles.Rlocation("_main/dotnet/test/common/appconfig.json"); + } + catch (FileNotFoundException) + { + dataFilePath = "appconfig.json"; + } + string currentDirectory = this.CurrentDirectory; - string content = File.ReadAllText(dataFilePath); - TestEnvironment env = JsonConvert.DeserializeObject(content); + string content = File.ReadAllText(dataFilePath); + TestEnvironment env = JsonConvert.DeserializeObject(content); - string activeDriverConfig = System.Environment.GetEnvironmentVariable("ACTIVE_DRIVER_CONFIG") ?? TestContext.Parameters.Get("ActiveDriverConfig", env.ActiveDriverConfig); - string driverServiceLocation = System.Environment.GetEnvironmentVariable("DRIVER_SERVICE_LOCATION") ?? TestContext.Parameters.Get("DriverServiceLocation", env.DriverServiceLocation); + string activeDriverConfig = System.Environment.GetEnvironmentVariable("ACTIVE_DRIVER_CONFIG") ?? TestContext.Parameters.Get("ActiveDriverConfig", env.ActiveDriverConfig); + string driverServiceLocation = System.Environment.GetEnvironmentVariable("DRIVER_SERVICE_LOCATION") ?? TestContext.Parameters.Get("DriverServiceLocation", env.DriverServiceLocation); - string browserLocation = System.Environment.GetEnvironmentVariable("BROWSER_LOCATION") ?? TestContext.Parameters.Get("BrowserLocation", string.Empty); + string browserLocation = System.Environment.GetEnvironmentVariable("BROWSER_LOCATION") ?? TestContext.Parameters.Get("BrowserLocation", string.Empty); - string activeWebsiteConfig = TestContext.Parameters.Get("ActiveWebsiteConfig", env.ActiveWebsiteConfig); - DriverConfig driverConfig = env.DriverConfigs[activeDriverConfig]; - WebsiteConfig websiteConfig = env.WebSiteConfigs[activeWebsiteConfig]; + string activeWebsiteConfig = TestContext.Parameters.Get("ActiveWebsiteConfig", env.ActiveWebsiteConfig); + DriverConfig driverConfig = env.DriverConfigs[activeDriverConfig]; + WebsiteConfig websiteConfig = env.WebSiteConfigs[activeWebsiteConfig]; - int port = PortUtilities.FindFreePort(); - websiteConfig.Port = port.ToString(); + int port = PortUtilities.FindFreePort(); + websiteConfig.Port = port.ToString(); - TestWebServerConfig webServerConfig = env.TestWebServerConfig; - webServerConfig.CaptureConsoleOutput = TestContext.Parameters.Get("CaptureWebServerOutput", env.TestWebServerConfig.CaptureConsoleOutput); - webServerConfig.HideCommandPromptWindow = TestContext.Parameters.Get("HideWebServerCommandPrompt", env.TestWebServerConfig.HideCommandPromptWindow); - webServerConfig.JavaHomeDirectory = TestContext.Parameters.Get("WebServerJavaHome", env.TestWebServerConfig.JavaHomeDirectory); - webServerConfig.Port = websiteConfig.Port; + TestWebServerConfig webServerConfig = env.TestWebServerConfig; + webServerConfig.CaptureConsoleOutput = TestContext.Parameters.Get("CaptureWebServerOutput", env.TestWebServerConfig.CaptureConsoleOutput); + webServerConfig.HideCommandPromptWindow = TestContext.Parameters.Get("HideWebServerCommandPrompt", env.TestWebServerConfig.HideCommandPromptWindow); + webServerConfig.JavaHomeDirectory = TestContext.Parameters.Get("WebServerJavaHome", env.TestWebServerConfig.JavaHomeDirectory); + webServerConfig.Port = websiteConfig.Port; - this.driverFactory = new DriverFactory(driverServiceLocation, browserLocation); - this.driverFactory.DriverStarting += OnDriverStarting; + this.driverFactory = new DriverFactory(driverServiceLocation, browserLocation); + this.driverFactory.DriverStarting += OnDriverStarting; - // Search for the driver type in the all assemblies, - // bazel uses unpredictable assembly names to execute tests - driverType = AppDomain.CurrentDomain.GetAssemblies() - .Reverse() - .Select(assembly => assembly.GetType(driverConfig.DriverTypeName)) - .FirstOrDefault(t => t != null); + // Search for the driver type in the all assemblies, + // bazel uses unpredictable assembly names to execute tests + driverType = AppDomain.CurrentDomain.GetAssemblies() + .Reverse() + .Select(assembly => assembly.GetType(driverConfig.DriverTypeName)) + .FirstOrDefault(t => t != null); - if (driverType == null) - { - throw new ArgumentOutOfRangeException($"Unable to find driver type {driverConfig.DriverTypeName}"); - } + if (driverType == null) + { + throw new ArgumentOutOfRangeException($"Unable to find driver type {driverConfig.DriverTypeName}"); + } Browser = driverConfig.BrowserValue; RemoteCapabilities = driverConfig.RemoteCapabilities; UrlBuilder = new UrlBuilder(websiteConfig); - // When run using the `bazel test` command, the following environment - // variable will be set. If not set, we're running from a build system - // outside Bazel, and need to locate the directory containing the jar. - string projectRoot = System.Environment.GetEnvironmentVariable("TEST_SRCDIR"); - if (string.IsNullOrEmpty(projectRoot)) - { - // Walk up the directory tree until we find ourselves in a directory - // where the path to the Java web server can be determined. - bool continueTraversal = true; - DirectoryInfo info = new DirectoryInfo(currentDirectory); - while (continueTraversal) + // When run using the `bazel test` command, the following environment + // variable will be set. If not set, we're running from a build system + // outside Bazel, and need to locate the directory containing the jar. + string projectRoot = System.Environment.GetEnvironmentVariable("TEST_SRCDIR"); + if (string.IsNullOrEmpty(projectRoot)) { - if (info == info.Root) - { - break; - } - - foreach (var childDir in info.EnumerateDirectories()) + // Walk up the directory tree until we find ourselves in a directory + // where the path to the Java web server can be determined. + bool continueTraversal = true; + DirectoryInfo info = new DirectoryInfo(currentDirectory); + while (continueTraversal) { - // Case 1: The current directory of this assembly is in the - // same direct sub-tree as the Java targets (usually meaning - // executing tests from the same build system as that which - // builds the Java targets). - // If we find a child directory named "java", then the web - // server should be able to be found under there. - if (string.Compare(childDir.Name, "java", StringComparison.OrdinalIgnoreCase) == 0) + if (info == info.Root) { - continueTraversal = false; break; } - // Case 2: The current directory of this assembly is a different - // sub-tree as the Java targets (usually meaning executing tests - // from a different build system as that which builds the Java - // targets). - // If we travel to a place in the tree where there is a child - // directory named "bazel-bin", the web server should be found - // in the "java" subdirectory of that directory. - if (string.Compare(childDir.Name, "bazel-bin", StringComparison.OrdinalIgnoreCase) == 0) + foreach (var childDir in info.EnumerateDirectories()) { - string javaOutDirectory = Path.Combine(childDir.FullName, "java"); - if (Directory.Exists(javaOutDirectory)) + // Case 1: The current directory of this assembly is in the + // same direct sub-tree as the Java targets (usually meaning + // executing tests from the same build system as that which + // builds the Java targets). + // If we find a child directory named "java", then the web + // server should be able to be found under there. + if (string.Compare(childDir.Name, "java", StringComparison.OrdinalIgnoreCase) == 0) { - info = childDir; continueTraversal = false; break; } + + // Case 2: The current directory of this assembly is a different + // sub-tree as the Java targets (usually meaning executing tests + // from a different build system as that which builds the Java + // targets). + // If we travel to a place in the tree where there is a child + // directory named "bazel-bin", the web server should be found + // in the "java" subdirectory of that directory. + if (string.Compare(childDir.Name, "bazel-bin", StringComparison.OrdinalIgnoreCase) == 0) + { + string javaOutDirectory = Path.Combine(childDir.FullName, "java"); + if (Directory.Exists(javaOutDirectory)) + { + info = childDir; + continueTraversal = false; + break; + } + } } - } - if (continueTraversal) - { - info = info.Parent; + if (continueTraversal) + { + info = info.Parent; + } } - } - projectRoot = info.FullName; - } - else - { - projectRoot += "/_main"; - } - - // Find selenium-manager binary. - try - { - string managerFilePath = ""; - runfiles ??= Runfiles.Create(); - - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + projectRoot = info.FullName; + } + else { - managerFilePath = runfiles.Rlocation("_main/dotnet/src/webdriver/manager/windows/selenium-manager.exe"); + projectRoot += "/_main"; } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + + // Find selenium-manager binary. + try { - managerFilePath = runfiles.Rlocation("_main/dotnet/src/webdriver/manager/linux/selenium-manager"); + string managerFilePath = ""; + runfiles ??= Runfiles.Create(); + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + managerFilePath = runfiles.Rlocation("_main/dotnet/src/webdriver/manager/windows/selenium-manager.exe"); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + managerFilePath = runfiles.Rlocation("_main/dotnet/src/webdriver/manager/linux/selenium-manager"); + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + { + managerFilePath = runfiles.Rlocation("_main/dotnet/src/webdriver/manager/macos/selenium-manager"); + } + + System.Environment.SetEnvironmentVariable("SE_MANAGER_PATH", managerFilePath); } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + catch (FileNotFoundException) { - managerFilePath = runfiles.Rlocation("_main/dotnet/src/webdriver/manager/macos/selenium-manager"); + // Use the default one. } - System.Environment.SetEnvironmentVariable("SE_MANAGER_PATH", managerFilePath); - } - catch (FileNotFoundException) - { - // Use the default one. - } - WebServer = new TestWebServer(projectRoot, webServerConfig); bool autoStartRemoteServer = false; if (Browser == Browser.Remote) @@ -197,25 +197,25 @@ private EnvironmentManager() CloseCurrentDriver(); } -public event EventHandler DriverStarting; + public event EventHandler DriverStarting; public static EnvironmentManager Instance => instance ??= new EnvironmentManager(); public Browser Browser { get; } -public string CurrentDirectory -{ - get + public string CurrentDirectory { - string assemblyLocation = Path.GetDirectoryName(typeof(EnvironmentManager).Assembly.Location); - string testDirectory = TestContext.CurrentContext.TestDirectory; - if (assemblyLocation != testDirectory) + get { - return assemblyLocation; + string assemblyLocation = Path.GetDirectoryName(typeof(EnvironmentManager).Assembly.Location); + string testDirectory = TestContext.CurrentContext.TestDirectory; + if (assemblyLocation != testDirectory) + { + return assemblyLocation; + } + return testDirectory; } - return testDirectory; } -} public TestWebServer WebServer { get; } @@ -230,22 +230,22 @@ public IWebDriver GetCurrentDriver() return driver ?? CreateFreshDriver(); } -public IWebDriver CreateDriverInstance() -{ - return driverFactory.CreateDriver(driverType); -} + public IWebDriver CreateDriverInstance() + { + return driverFactory.CreateDriver(driverType); + } -public IWebDriver CreateDriverInstance(DriverOptions options) -{ - return driverFactory.CreateDriverWithOptions(driverType, options); -} + public IWebDriver CreateDriverInstance(DriverOptions options) + { + return driverFactory.CreateDriverWithOptions(driverType, options); + } -public IWebDriver CreateFreshDriver() -{ - CloseCurrentDriver(); - driver = CreateDriverInstance(); - return driver; -} + public IWebDriver CreateFreshDriver() + { + CloseCurrentDriver(); + driver = CreateDriverInstance(); + return driver; + } public void CloseCurrentDriver() { @@ -253,11 +253,11 @@ public void CloseCurrentDriver() driver = null; } -protected void OnDriverStarting(object sender, DriverStartingEventArgs e) -{ - if (this.DriverStarting != null) + protected void OnDriverStarting(object sender, DriverStartingEventArgs e) { - this.DriverStarting(sender, e); + if (this.DriverStarting != null) + { + this.DriverStarting(sender, e); + } } } -} \ No newline at end of file From e7fb011f2f6a66735095cf071487dec1da57fd1d Mon Sep 17 00:00:00 2001 From: Michael Render Date: Tue, 27 May 2025 12:29:53 -0400 Subject: [PATCH 3/4] Fix whitespace --- dotnet/test/common/TestUtilities.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dotnet/test/common/TestUtilities.cs b/dotnet/test/common/TestUtilities.cs index 963d3e83c508f..28e543604d0ff 100644 --- a/dotnet/test/common/TestUtilities.cs +++ b/dotnet/test/common/TestUtilities.cs @@ -118,4 +118,4 @@ public static bool IsNativeEventsEnabled(IWebDriver driver) return false; } -} \ No newline at end of file +} From f22ef2c6990aa084a0b8e2be452076286a153300 Mon Sep 17 00:00:00 2001 From: Michael Render Date: Tue, 27 May 2025 12:47:40 -0400 Subject: [PATCH 4/4] Fix newline again --- dotnet/test/firefox/FirefoxProfileTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dotnet/test/firefox/FirefoxProfileTests.cs b/dotnet/test/firefox/FirefoxProfileTests.cs index 7db0ee2f208bd..aed4344cfda2c 100644 --- a/dotnet/test/firefox/FirefoxProfileTests.cs +++ b/dotnet/test/firefox/FirefoxProfileTests.cs @@ -106,4 +106,4 @@ private List ReadGeneratedProperties() } return generatedProperties; } -} \ No newline at end of file +}