Skip to content

Commit 6411edd

Browse files
authored
Merge branch 'trunk' into pinned-browser-updates
2 parents c81ba3b + e2fc5e8 commit 6411edd

File tree

10 files changed

+342
-35
lines changed

10 files changed

+342
-35
lines changed

.skipped-tests

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
-//dotnet/test/common:NetworkInterceptionTests-chrome
22
-//dotnet/test/common:NetworkInterceptionTests-edge
3+
-//dotnet/test/firefox:FirefoxDriverTest-firefox
34
-//java/test/org/openqa/selenium/chrome:ChromeDriverFunctionalTest
45
-//java/test/org/openqa/selenium/chrome:ChromeDriverFunctionalTest-remote
56
-//java/test/org/openqa/selenium/edge:EdgeDriverFunctionalTest

dotnet/src/webdriver/DriverService.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ protected virtual void Dispose(bool disposing)
284284
/// Raises the <see cref="DriverProcessStarting"/> event.
285285
/// </summary>
286286
/// <param name="eventArgs">A <see cref="DriverProcessStartingEventArgs"/> that contains the event data.</param>
287-
protected void OnDriverProcessStarting(DriverProcessStartingEventArgs eventArgs)
287+
protected virtual void OnDriverProcessStarting(DriverProcessStartingEventArgs eventArgs)
288288
{
289289
if (eventArgs == null)
290290
{
@@ -298,7 +298,7 @@ protected void OnDriverProcessStarting(DriverProcessStartingEventArgs eventArgs)
298298
/// Raises the <see cref="DriverProcessStarted"/> event.
299299
/// </summary>
300300
/// <param name="eventArgs">A <see cref="DriverProcessStartedEventArgs"/> that contains the event data.</param>
301-
protected void OnDriverProcessStarted(DriverProcessStartedEventArgs eventArgs)
301+
protected virtual void OnDriverProcessStarted(DriverProcessStartedEventArgs eventArgs)
302302
{
303303
if (eventArgs == null)
304304
{

dotnet/src/webdriver/Firefox/FirefoxDriverService.cs

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
using System.Globalization;
2323
using System.IO;
2424
using System.Text;
25+
using System.Threading.Tasks;
2526

2627
namespace OpenQA.Selenium.Firefox;
2728

@@ -32,6 +33,11 @@ public sealed class FirefoxDriverService : DriverService
3233
{
3334
private const string DefaultFirefoxDriverServiceFileName = "geckodriver";
3435

36+
/// <summary>
37+
/// Process management fields for the log writer.
38+
/// </summary>
39+
private StreamWriter? logWriter;
40+
3541
/// <summary>
3642
/// Initializes a new instance of the <see cref="FirefoxDriverService"/> class.
3743
/// </summary>
@@ -87,6 +93,16 @@ protected override DriverOptions GetDefaultDriverOptions()
8793
/// </summary>
8894
public bool OpenBrowserToolbox { get; set; }
8995

96+
/// <summary>
97+
/// Gets or sets the file path where log output should be written.
98+
/// </summary>
99+
/// <remarks>
100+
/// A <see langword="null"/> or <see cref="string.Empty"/> value indicates no log file to specify.
101+
/// This approach takes the process output and redirects it to a file because GeckoDriver does not
102+
/// offer a way to specify a log file path directly.
103+
/// </remarks>
104+
public string? LogPath { get; set; }
105+
90106
/// <summary>
91107
/// Gets or sets the level at which log output is displayed.
92108
/// </summary>
@@ -177,6 +193,75 @@ protected override string CommandLineArguments
177193
}
178194
}
179195

196+
/// <summary>
197+
/// Handles the event when the driver service process is starting.
198+
/// </summary>
199+
/// <param name="eventArgs">The event arguments containing information about the driver service process.</param>
200+
/// <remarks>
201+
/// This method initializes a log writer if a log path is specified and redirects output streams to capture logs.
202+
/// </remarks>
203+
protected override void OnDriverProcessStarting(DriverProcessStartingEventArgs eventArgs)
204+
{
205+
if (!string.IsNullOrEmpty(this.LogPath))
206+
{
207+
string? directory = Path.GetDirectoryName(this.LogPath);
208+
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
209+
{
210+
Directory.CreateDirectory(directory);
211+
}
212+
213+
// Initialize the log writer
214+
logWriter = new StreamWriter(this.LogPath, append: true) { AutoFlush = true };
215+
216+
// Configure process to redirect output
217+
eventArgs.DriverServiceProcessStartInfo.RedirectStandardOutput = true;
218+
eventArgs.DriverServiceProcessStartInfo.RedirectStandardError = true;
219+
}
220+
221+
base.OnDriverProcessStarting(eventArgs);
222+
}
223+
224+
/// <summary>
225+
/// Handles the event when the driver process has started.
226+
/// </summary>
227+
/// <param name="eventArgs">The event arguments containing information about the started driver process.</param>
228+
/// <remarks>
229+
/// This method reads the output and error streams asynchronously and writes them to the log file if available.
230+
/// </remarks>
231+
protected override void OnDriverProcessStarted(DriverProcessStartedEventArgs eventArgs)
232+
{
233+
if (logWriter == null) return;
234+
if (eventArgs.StandardOutputStreamReader != null)
235+
{
236+
_ = Task.Run(() => ReadStreamAsync(eventArgs.StandardOutputStreamReader));
237+
}
238+
239+
if (eventArgs.StandardErrorStreamReader != null)
240+
{
241+
_ = Task.Run(() => ReadStreamAsync(eventArgs.StandardErrorStreamReader));
242+
}
243+
244+
base.OnDriverProcessStarted(eventArgs);
245+
}
246+
247+
/// <summary>
248+
/// Disposes of the resources used by the <see cref="FirefoxDriverService"/> instance.
249+
/// </summary>
250+
/// <param name="disposing">A value indicating whether the method is being called from Dispose.</param>
251+
/// <remarks>
252+
/// If disposing is true, it disposes of the log writer if it exists.
253+
/// </remarks>
254+
protected override void Dispose(bool disposing)
255+
{
256+
if (logWriter != null && disposing)
257+
{
258+
logWriter.Dispose();
259+
logWriter = null;
260+
}
261+
262+
base.Dispose(disposing);
263+
}
264+
180265
/// <summary>
181266
/// Creates a default instance of the FirefoxDriverService.
182267
/// </summary>
@@ -258,4 +343,24 @@ private static string FirefoxDriverServiceFileName()
258343

259344
return fileName;
260345
}
346+
347+
private async Task ReadStreamAsync(StreamReader reader)
348+
{
349+
try
350+
{
351+
string? line;
352+
while ((line = await reader.ReadLineAsync()) != null)
353+
{
354+
if (logWriter != null)
355+
{
356+
logWriter.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} {line}");
357+
}
358+
}
359+
}
360+
catch (Exception ex)
361+
{
362+
// Log or handle the exception appropriately
363+
System.Diagnostics.Debug.WriteLine($"Error reading stream: {ex.Message}");
364+
}
365+
}
261366
}

dotnet/test/firefox/BUILD.bazel

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
load("//dotnet:defs.bzl", "dotnet_nunit_test_suite", "framework")
2+
3+
dotnet_nunit_test_suite(
4+
name = "LargeTests",
5+
size = "large",
6+
srcs = glob(
7+
[
8+
"**/*Test.cs",
9+
"**/*Tests.cs",
10+
],
11+
) + [
12+
"//dotnet/test/common:assembly-fixtures",
13+
],
14+
browsers = [
15+
"firefox",
16+
],
17+
data = [
18+
"//dotnet/test/common:test-data",
19+
],
20+
target_frameworks = ["net8.0"],
21+
deps = [
22+
"//dotnet/src/support",
23+
"//dotnet/src/webdriver:webdriver-net8.0",
24+
"//dotnet/test/common:fixtures",
25+
framework("nuget", "NUnit"),
26+
],
27+
)
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// <copyright file="FirefoxDriverServiceTest.cs" company="Selenium Committers">
2+
// Licensed to the Software Freedom Conservancy (SFC) under one
3+
// or more contributor license agreements. See the NOTICE file
4+
// distributed with this work for additional information
5+
// regarding copyright ownership. The SFC licenses this file
6+
// to you under the Apache License, Version 2.0 (the
7+
// "License"); you may not use this file except in compliance
8+
// with the License. You may obtain a copy of the License at
9+
//
10+
// http://www.apache.org/licenses/LICENSE-2.0
11+
//
12+
// Unless required by applicable law or agreed to in writing,
13+
// software distributed under the License is distributed on an
14+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
// KIND, either express or implied. See the License for the
16+
// specific language governing permissions and limitations
17+
// under the License.
18+
// </copyright>
19+
20+
using NUnit.Framework;
21+
using System.IO;
22+
23+
namespace OpenQA.Selenium.Firefox;
24+
25+
[TestFixture]
26+
public class FirefoxDriverServiceTest : DriverTestFixture
27+
{
28+
[Test]
29+
public void ShouldRedirectGeckoDriverLogsToFile()
30+
{
31+
FirefoxOptions options = new FirefoxOptions();
32+
string logPath = Path.GetTempFileName();
33+
options.LogLevel = FirefoxDriverLogLevel.Trace;
34+
35+
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();
36+
service.LogPath = logPath;
37+
38+
IWebDriver driver2 = new FirefoxDriver(service, options);
39+
40+
try
41+
{
42+
Assert.That(File.Exists(logPath), Is.True);
43+
string logContent = File.ReadAllText(logPath);
44+
Assert.That(logContent, Does.Contain("geckodriver"));
45+
}
46+
finally
47+
{
48+
driver2.Quit();
49+
File.Delete(logPath);
50+
}
51+
}
52+
53+
}

java/src/org/openqa/selenium/remote/RemoteWebDriver.java

Lines changed: 46 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@
8888
import org.openqa.selenium.remote.http.ClientConfig;
8989
import org.openqa.selenium.remote.http.ConnectionFailedException;
9090
import org.openqa.selenium.remote.http.HttpClient;
91+
import org.openqa.selenium.remote.service.DriverCommandExecutor;
9192
import org.openqa.selenium.remote.tracing.TracedHttpClient;
9293
import org.openqa.selenium.remote.tracing.Tracer;
9394
import org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer;
@@ -241,46 +242,58 @@ protected void startSession(Capabilities capabilities) {
241242
checkNonW3CCapabilities(capabilities);
242243
checkChromeW3CFalse(capabilities);
243244

244-
Response response = execute(DriverCommand.NEW_SESSION(singleton(capabilities)));
245+
try {
246+
Response response = execute(DriverCommand.NEW_SESSION(singleton(capabilities)));
245247

246-
if (response == null) {
247-
throw new SessionNotCreatedException(
248-
"The underlying command executor returned a null response.");
249-
}
248+
if (response == null) {
249+
throw new SessionNotCreatedException(
250+
"The underlying command executor returned a null response.");
251+
}
250252

251-
Object responseValue = response.getValue();
253+
Object responseValue = response.getValue();
252254

253-
if (responseValue == null) {
254-
throw new SessionNotCreatedException(
255-
"The underlying command executor returned a response without payload: " + response);
256-
}
255+
if (responseValue == null) {
256+
throw new SessionNotCreatedException(
257+
"The underlying command executor returned a response without payload: " + response);
258+
}
257259

258-
if (!(responseValue instanceof Map)) {
259-
throw new SessionNotCreatedException(
260-
"The underlying command executor returned a response with a non well formed payload: "
261-
+ response);
262-
}
260+
if (!(responseValue instanceof Map)) {
261+
throw new SessionNotCreatedException(
262+
"The underlying command executor returned a response with a non well formed payload: "
263+
+ response);
264+
}
263265

264-
@SuppressWarnings("unchecked")
265-
Map<String, Object> rawCapabilities = (Map<String, Object>) responseValue;
266-
MutableCapabilities returnedCapabilities = new MutableCapabilities(rawCapabilities);
267-
String platformString = (String) rawCapabilities.get(PLATFORM_NAME);
268-
Platform platform;
269-
try {
270-
if (platformString == null || platformString.isEmpty()) {
271-
platform = Platform.ANY;
272-
} else {
273-
platform = Platform.fromString(platformString);
266+
@SuppressWarnings("unchecked")
267+
Map<String, Object> rawCapabilities = (Map<String, Object>) responseValue;
268+
MutableCapabilities returnedCapabilities = new MutableCapabilities(rawCapabilities);
269+
String platformString = (String) rawCapabilities.get(PLATFORM_NAME);
270+
Platform platform;
271+
try {
272+
if (platformString == null || platformString.isEmpty()) {
273+
platform = Platform.ANY;
274+
} else {
275+
platform = Platform.fromString(platformString);
276+
}
277+
} catch (WebDriverException e) {
278+
// The server probably responded with a name matching the os.name
279+
// system property. Try to recover and parse this.
280+
platform = Platform.extractFromSysProperty(platformString);
274281
}
275-
} catch (WebDriverException e) {
276-
// The server probably responded with a name matching the os.name
277-
// system property. Try to recover and parse this.
278-
platform = Platform.extractFromSysProperty(platformString);
282+
returnedCapabilities.setCapability(PLATFORM_NAME, platform);
283+
284+
this.capabilities = returnedCapabilities;
285+
sessionId = new SessionId(response.getSessionId());
286+
} catch (Exception e) {
287+
// If session creation fails, stop the driver service to prevent zombie processes
288+
if (executor instanceof DriverCommandExecutor) {
289+
try {
290+
((DriverCommandExecutor) executor).close();
291+
} catch (Exception ignored) {
292+
// Ignore cleanup exceptions, we'll propagate the original failure
293+
}
294+
}
295+
throw e;
279296
}
280-
returnedCapabilities.setCapability(PLATFORM_NAME, platform);
281-
282-
this.capabilities = returnedCapabilities;
283-
sessionId = new SessionId(response.getSessionId());
284297
}
285298

286299
public ErrorHandler getErrorHandler() {
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Licensed to the Software Freedom Conservancy (SFC) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The SFC licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
package org.openqa.selenium.chrome;
19+
20+
import static org.assertj.core.api.Assertions.assertThat;
21+
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
22+
import static org.mockito.Mockito.spy;
23+
24+
import org.junit.jupiter.api.Tag;
25+
import org.junit.jupiter.api.Test;
26+
import org.openqa.selenium.SessionNotCreatedException;
27+
28+
@Tag("UnitTests")
29+
class ChromeDriverServiceCleanupTest {
30+
31+
@Test
32+
void shouldStopServiceWhenSessionCreationFails() {
33+
// Create a Chrome options that will cause session creation to fail
34+
ChromeOptions options = new ChromeOptions();
35+
options.addArguments("--user-data-dir=/no/such/location");
36+
37+
// Create a service
38+
ChromeDriverService service = ChromeDriverService.createDefaultService();
39+
ChromeDriverService serviceSpy = spy(service);
40+
41+
// Attempt to create driver - should fail and cleanup the service
42+
assertThatExceptionOfType(SessionNotCreatedException.class)
43+
.isThrownBy(() -> new ChromeDriver(serviceSpy, options));
44+
45+
// Verify that the service was stopped
46+
assertThat(serviceSpy.isRunning()).isFalse();
47+
}
48+
}

0 commit comments

Comments
 (0)