-
-
Notifications
You must be signed in to change notification settings - Fork 8.4k
.pr_agent_accepted_suggestions
PR 15676 (2025-04-28) |
[possible issue] Fix inconsistent log message
✅ Fix inconsistent log message
The log message doesn't match the test expectation. The test expects a message containing "No valid process exit status" but the actual message uses "Invalid process exit status". Update the log message to match the test expectation.
rb/lib/selenium/webdriver/common/selenium_manager.rb [108-118]
def validate_command_result(command, status, result, stderr)
if status.nil? || status.exitstatus.nil?
- WebDriver.logger.info("Invalid process exit status for: #{command}. Assuming success if result is present.",
+ WebDriver.logger.info("No valid process exit status for: #{command}. Assuming success if result is present.",
id: :selenium_manager)
end
return unless status&.exitstatus&.positive? || result.nil?
raise Error::WebDriverError,
"Unsuccessful command executed: #{command} - Code #{status&.exitstatus}\n#{result}\n#{stderr}"
end
Suggestion importance[1-10]: 6
__
Why: The suggestion correctly identifies a mismatch between the log message in the validate_command_result
method and the expectation in the corresponding new test in selenium_manager_spec.rb
. Applying the fix ensures the test passes and maintains consistency.
PR 15643 (2025-04-19) |
[general] Add missing autoflake option
✅ Add missing autoflake option
Consider adding the remove-all-unused-imports option to the autoflake configuration to ensure all unused imports are removed, which aligns with the PR's goal of adding autoflake for linting.
[tool.autoflake]
exclude = "selenium/webdriver/common/devtools"
ignore-pass-after-docstring = true
in-place = true
quiet = true
recursive = true
remove-duplicate-keys = true
remove-unused-variables = true
+remove-all-unused-imports = true
Suggestion importance[1-10]: 6
__
Why: The suggestion adds the 'remove-all-unused-imports' option to autoflake configuration, which aligns with the PR's goal of enhancing linting capabilities. This is a relevant improvement that would make the autoflake tool more effective at removing unused imports.
[possible issue] Fix flake8 configuration
✅ Fix flake8 configuration
The flake8-pyproject package is added as a dependency in tox.ini, but the configuration in pyproject.toml might not work as expected. Flake8 traditionally doesn't read from pyproject.toml natively - it requires the flake8-pyproject plugin to be properly configured.
[tool.flake8]
exclude = "selenium/webdriver/common/devtools"
# Disable E501 once line length is better handled
extend-ignore = ["E501", "E203"]
# This does nothing for now as E501 is ignored
max-line-length = 120
-min-python-version = 3.9
+min_python_version = "3.9"
Suggestion importance[1-10]: 5
__
Why: The suggestion correctly identifies a configuration issue with flake8 in pyproject.toml. The parameter should be min_python_version with an underscore instead of min-python-version with a hyphen, and the value should be a string "3.9" rather than a number.
[general] Remove only_modified isort option
✅ Remove only_modified isort option
The only_modified option in isort configuration will limit isort to only process modified files. This could lead to inconsistent formatting across the codebase. For a linting tool in a CI environment, it's better to ensure all files follow the same standard.
[tool.isort]
# isort is a common python tool for keeping imports nicely formatted.
# Automatically keep imports alphabetically sorted, on single lines in
# PEP recommended sections (https://peps.python.org/pep-0008/#imports)
# files or individual lines can be ignored via `# isort:skip|# isort:skip_file`.
force_single_line = true
profile = "black"
py_version = 39
-only_modified = true
Suggestion importance[1-10]: 8
__
Why: The suggestion correctly identifies a potential issue with the added "only_modified" option, which could lead to inconsistent formatting across the codebase. Removing this option would ensure consistent formatting standards are applied to all files.
PR 15619 (2025-04-12) |
[general] Fix typo in function name
✅ Fix typo in function name
Fix the typo in the test function name. "paraeter" should be "parameter".
py/test/selenium/webdriver/remote/remote_tests.py [25]
-def test_remote_webdriver_requires_options_paraeter():
+def test_remote_webdriver_requires_options_parameter():
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies a typo in the test function name where "paraeter" should be "parameter". This is a valid improvement for code readability and maintainability, ensuring consistent and correct naming conventions.
[general] Rename test function
✅ Rename test function
The test function name test_remote_webdriver_requires_options_kwarg() implies that options is a keyword-only argument, but in the implementation it's a regular parameter. Consider renaming the test function to better reflect what's being tested.
py/test/selenium/webdriver/remote/remote_tests.py [25-32]
-def test_remote_webdriver_requires_options_kwarg():
+def test_remote_webdriver_requires_options_parameter():
msg = "missing 1 required keyword-only argument: 'options' (instance of driver `options.Options` class)"
with pytest.raises(TypeError, match=re.escape(msg)):
webdriver.Remote()
with pytest.raises(TypeError, match=re.escape(msg)):
webdriver.Remote(None)
with pytest.raises(TypeError, match=re.escape(msg)):
webdriver.Remote(options=None)
Suggestion importance[1-10]: 5
__
Why: The suggestion correctly identifies a mismatch between the test function name and the error message. The error message refers to 'options' as a "keyword-only argument" while the function name implies it's a keyword argument, but the implementation treats it as a regular parameter. Renaming the function improves clarity and consistency.
PR 15616 (2025-04-11) |
[possible issue] Prevent removing default context
✅ Prevent removing default context
Add validation to prevent removing the "default" user context. The docstring mentions that an exception will be raised if the user context ID is "default", but there's no actual validation in the code to prevent this operation.
py/selenium/webdriver/common/bidi/browser.py [168-180]
def remove_user_context(self, user_context_id: str) -> None:
"""Removes a user context.
Parameters:
-----------
user_context_id: The ID of the user context to remove.
Raises:
------
Exception: If the user context ID is "default" or does not exist.
"""
+ if user_context_id == "default":
+ raise Exception("Cannot remove the default user context")
+
params = {"userContext": user_context_id}
self.conn.execute(command_builder("browser.removeUserContext", params))
Suggestion importance[1-10]: 9
__
Why: The suggestion adds critical validation to prevent removing the "default" user context, which aligns with the documented behavior in the docstring. Without this check, users could attempt to remove the default context, potentially causing system instability or unexpected behavior.
PR 15615 (2025-04-11) |
[general] Move import to module level
✅ Move import to module level
Move the import statement to the top of the file with other imports rather than inside the method. Importing within a method can cause performance issues if the method is called frequently, as the import operation will be repeated each time.
py/selenium/webdriver/remote/webdriver.py [1289-1294]
def get_bidi_session_status(self):
"""
Get the session status using WebDriver BiDi.
Returns information about whether a remote end is in a state
in which it can create new sessions.
Returns:
-------
dict
Dictionary containing the ready state (bool), message (str) and metadata
Example:
--------
>>> status = driver.get_bidi_session_status()
>>> print(status["ready"])
>>> print(status["message"])
"""
if not self._websocket_connection:
self._start_bidi()
- from selenium.webdriver.common.bidi.session import session_status
-
return self._websocket_connection.execute(session_status())
Suggestion importance[1-10]: 3
__
Why: Moving the import statement to the module level is a valid suggestion that follows Python best practices and could slightly improve performance if the method is called frequently. However, the impact is relatively minor as the performance difference would only be noticeable with frequent calls.
PR 15614 (2025-04-11) |
[general] Fix grammatical errors
✅ Fix grammatical errors
There's a grammatical error in the instructions about staging files after running black and isort. The phrase "should staged again" is incorrect and could confuse contributors.
py/docs/source/index.rst [178-180]
- `flake8` requires manual fixes
-- `black` will rewrite the violations automatically, however the files are unstaged and should staged again
-- `isort` will rewrite the violations automatically, however the files are unstaged and should staged again
+- `black` will rewrite the violations automatically, however the files are unstaged and should be staged again
+- `isort` will rewrite the violations automatically, however the files are unstaged and should be staged again
Suggestion importance[1-10]: 5
__
Why: The suggestion correctly identifies and fixes a grammatical error in the contributing instructions, changing "should staged again" to "should be staged again". While not affecting functionality, this improves clarity and professionalism of the documentation.
[general] Use specific Python version
✅ Use specific Python version
Using "latest" for Python version can lead to unexpected build failures when new Python versions are released. Specify a concrete Python version (like "3.11") to ensure build stability and reproducibility.
py/docs/.readthedocs.yaml [10-18]
build:
os: ubuntu-24.04
tools:
- python: "latest"
+ python: "3.11"
commands:
- pip install -r py/docs/requirements.txt
- pip install -r py/requirements.txt
- PYTHONPATH=py sphinx-autogen -o $READTHEDOCS_OUTPUT/html py/docs/source/api.rst
- PYTHONPATH=py sphinx-build -b html -d build/docs/doctrees py/docs/source $READTHEDOCS_OUTPUT/html
Suggestion importance[1-10]: 7
__
Why: Using a specific Python version instead of "latest" is a good practice for build stability and reproducibility. This change would prevent potential issues when new Python versions are released that might introduce compatibility problems.
[possible issue] Add PYTHONPATH to sphinx-build
✅ Add PYTHONPATH to sphinx-build
The PYTHONPATH environment variable is set only for the sphinx-autogen command but not for the sphinx-build command. This could lead to import errors during documentation building if the Python modules need to be imported from the py directory.
py/docs/.readthedocs.yaml [10-18]
build:
os: ubuntu-24.04
tools:
python: "latest"
commands:
- pip install -r py/docs/requirements.txt
- pip install -r py/requirements.txt
- PYTHONPATH=py sphinx-autogen -o $READTHEDOCS_OUTPUT/html py/docs/source/api.rst
- - sphinx-build -b html -d build/docs/doctrees py/docs/source $READTHEDOCS_OUTPUT/html
+ - PYTHONPATH=py sphinx-build -b html -d build/docs/doctrees py/docs/source $READTHEDOCS_OUTPUT/html
Suggestion importance[1-10]: 8
__
Why: This suggestion addresses a potential build failure issue. Setting PYTHONPATH for sphinx-autogen but not for sphinx-build could cause import errors during documentation generation since sphinx-build also needs to access Python modules in the py directory.
PR 15601 (2025-04-09) |
[possible issue] Ensure environment variable timing
✅ Ensure environment variable timing
Setting environment variables after the process has started may not affect Firefox's behavior. Environment variables should be set before Firefox is launched. Consider checking if this environment variable is being set early enough to affect Firefox's startup behavior.
# There are issues with window size/position when running Firefox
# under Wayland, so we use XWayland instead.
-os.environ['MOZ_ENABLE_WAYLAND'] = '0'
+# Set this before Firefox is launched to ensure it takes effect
+if 'MOZ_ENABLE_WAYLAND' not in os.environ:
+ os.environ['MOZ_ENABLE_WAYLAND'] = '0'
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies a potential issue with environment variable timing. Setting environment variables after process initialization may not affect Firefox's behavior, and the improved code adds a check to avoid overriding existing values, which is a good practice for environment configuration.
PR 15579 (2025-04-05) |
[possible issue] Missing driver cleanup
✅ Missing driver cleanup
The test is missing cleanup for driver2. If driver2 is successfully created, it should be quit in the finally block to properly release resources.
py/test/selenium/webdriver/chrome/chrome_service_tests.py [53-54]
finally:
driver1.quit()
+ if driver2:
+ driver2.quit()
Suggestion importance[1-10]: 9
__
Why: The suggestion correctly identifies a resource leak where driver2 is not being properly cleaned up in the finally block. This is a significant issue that could lead to resource leaks and potentially affect subsequent tests.
[possible issue] Handle undefined variable safely
✅ Handle undefined variable safely
The test is missing a reference to driver1 before quitting it in the finally block. Since driver1 is defined inside the try block, it might not exist if an exception occurs before its creation, causing a NameError.
py/test/selenium/webdriver/chrome/chrome_service_tests.py [54]
-driver1.quit()
+if 'driver1' in locals() and driver1:
+ driver1.quit()
Suggestion importance[1-10]: 9
__
Why: The suggestion correctly identifies a critical issue where the test could fail with a NameError if an exception occurs before driver1 is created. The improved code safely checks if driver1 exists before attempting to quit it, preventing potential test failures.
PR 15575 (2025-04-04) |
[possible issue] Check dictionary key exists
✅ Check dictionary key exists
The code doesn't check if the successId exists in the _pendingCommands dictionary before accessing it. This could lead to a KeyNotFoundException if a success message is received for a command ID that is not in the dictionary.
dotnet/src/webdriver/BiDi/Communication/Broker.cs [136-142]
try
{
var data = await _transport.ReceiveAsync(cancellationToken).ConfigureAwait(false);
Utf8JsonReader utfJsonReader = new(new ReadOnlySpan<byte>(data));
utfJsonReader.Read();
var messageType = utfJsonReader.GetDiscriminator("type");
switch (messageType)
{
case "success":
var successId = int.Parse(utfJsonReader.GetDiscriminator("id"));
- var successCommand = _pendingCommands[successId];
- var messageSuccess = JsonSerializer.Deserialize(ref utfJsonReader, successCommand.Item1.ResultType, _jsonSerializerContext);
+ if (_pendingCommands.TryGetValue(successId, out var successCommand))
+ {
+ var messageSuccess = JsonSerializer.Deserialize(ref utfJsonReader, successCommand.Item1.ResultType, _jsonSerializerContext);
- successCommand.Item2.SetResult(messageSuccess);
+ successCommand.Item2.SetResult(messageSuccess);
- _pendingCommands.TryRemove(successId, out _);
+ _pendingCommands.TryRemove(successId, out _);
+ }
break;
Suggestion importance[1-10]: 8
__
Why: This suggestion addresses a potential runtime exception by checking if the key exists in the dictionary before accessing it. Without this check, the code could throw a KeyNotFoundException if a success message is received for a command ID that isn't in the pending commands dictionary.
[possible issue] Check event handlers exist
✅ Check event handlers exist
The code doesn't check if the method exists in the _eventHandlers dictionary or if there are any handlers for that method before accessing it. This could lead to a KeyNotFoundException or InvalidOperationException (when calling First() on an empty collection) if an event is received for a method that has no registered handlers.
dotnet/src/webdriver/BiDi/Communication/Broker.cs [145-159]
case "event":
utfJsonReader.Read();
utfJsonReader.Read();
var method = utfJsonReader.GetString();
utfJsonReader.Read();
- // TODO: Just get type info from existing subscribers, should be better
- var type = _eventHandlers[method].First().EventArgsType;
+ if (_eventHandlers.TryGetValue(method, out var handlers) && handlers.Count > 0)
+ {
+ // TODO: Just get type info from existing subscribers, should be better
+ var type = handlers.First().EventArgsType;
- var eventArgs = (EventArgs)JsonSerializer.Deserialize(ref utfJsonReader, type, _jsonSerializerContext);
+ var eventArgs = (EventArgs)JsonSerializer.Deserialize(ref utfJsonReader, type, _jsonSerializerContext);
- var messageEvent = new MessageEvent(method, eventArgs);
- _pendingEvents.Add(messageEvent);
+ var messageEvent = new MessageEvent(method, eventArgs);
+ _pendingEvents.Add(messageEvent);
+ }
break;
Suggestion importance[1-10]: 8
__
Why: The suggestion prevents potential KeyNotFoundException and InvalidOperationException by checking if handlers exist for the event method before attempting to access them. This is an important defensive coding practice that improves error handling and robustness.
PR 15559 (2025-04-03) |
[general] Missing verification after alert dismissal
✅ Missing verification after alert dismissal
The test is missing an assertion to verify that the alert was properly dismissed. After dismissing the alert, add an assertion to confirm that the alert is no longer present and that the page is in the expected state.
py/test/selenium/webdriver/common/alerts_tests.py [187-196]
@pytest.mark.xfail_safari
def test_should_throw_an_exception_if_an_alert_has_not_been_dealt_with_and_dismiss_the_alert(driver, pages):
pages.load("alerts.html")
driver.find_element(By.ID, "alert").click()
WebDriverWait(driver, 5).until(EC.alert_is_present())
with pytest.raises(UnexpectedAlertPresentException):
driver.find_element(By.ID, "select").click()
alert = _wait_for_alert(driver)
alert.dismiss()
+
+ # Verify alert is dismissed
+ assert "Testing Alerts" == driver.title
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies that the test lacks verification after dismissing the alert. Adding an assertion to check the page title is a good practice to ensure the alert was properly dismissed and the page returned to its expected state.
PR 15555 (2025-04-02) |
[possible issue] Validate discriminator existence
✅ Validate discriminator existence
The method doesn't handle the case where the discriminator property isn't found in the JSON object. If the property doesn't exist, the method will return null, which could lead to unexpected behavior in the converters that use this method. Consider adding validation to throw a more descriptive exception when the discriminator property is missing.
dotnet/src/webdriver/BiDi/Communication/Json/Internal/JsonExtensions.cs [26-52]
public static string? GetDiscriminator(this ref Utf8JsonReader reader, string name)
{
Utf8JsonReader readerClone = reader;
if (readerClone.TokenType != JsonTokenType.StartObject)
throw new JsonException();
string? discriminator = null;
readerClone.Read();
while (readerClone.TokenType == JsonTokenType.PropertyName)
{
string? propertyName = readerClone.GetString();
readerClone.Read();
if (propertyName == name)
{
discriminator = readerClone.GetString();
break;
}
readerClone.Skip();
readerClone.Read();
}
+ if (discriminator == null)
+ throw new JsonException($"Required discriminator property '{name}' not found in JSON object.");
+
return discriminator;
}
Suggestion importance[1-10]: 8
__
Why: The suggestion addresses a potential bug where missing discriminator properties would return null without error, causing silent failures in the converters. Adding validation with a descriptive exception improves error handling and debugging significantly.
PR 15532 (2025-03-28) |
[general] Remove redundant array conversion
✅ Remove redundant array conversion
The method is converting the array twice unnecessarily. The convertedArray variable is created but never used, and then the conversion is performed again in the return statement.
dotnet/src/webdriver/BiDi/Modules/Script/LocalValue.cs [200-209]
public static LocalValue ConvertFrom(object?[]? values)
{
if (values is null)
{
return new NullLocalValue();
}
LocalValue[] convertedArray = Array.ConvertAll(values, ConvertFrom);
- return new ArrayLocalValue(Array.ConvertAll(values, ConvertFrom));
+ return new ArrayLocalValue(convertedArray);
}
Suggestion importance[1-10]: 9
__
Why: The suggestion correctly identifies a significant bug where the array is converted twice unnecessarily. The code creates a convertedArray
variable but then ignores it, performing the conversion again in the return statement. This wastes CPU cycles and memory, potentially impacting performance for large arrays.
PR 15521 (2025-03-27) |
[learned best practice] Use safe type checking with the 'as' operator instead of direct casting to prevent potential InvalidCastException
✅ Use safe type checking with the 'as' operator instead of direct casting to prevent potential InvalidCastException
The current implementation of ThrowOnError() uses a direct cast to EvaluateResultException without checking if the object is actually of that type. If this is neither EvaluateResultSuccess nor EvaluateResultException, it will throw an InvalidCastException. Use the as operator with null checking to make the code more robust and prevent potential runtime exceptions.
dotnet/src/webdriver/BiDi/Modules/Script/EvaluateCommand.cs [44-52]
public EvaluateResultSuccess ThrowOnError()
{
if (this is EvaluateResultSuccess success)
{
return success;
}
- throw new ScriptEvaluateException((EvaluateResultException)this);
+ var exception = this as EvaluateResultException;
+ if (exception != null)
+ {
+ throw new ScriptEvaluateException(exception);
+ }
+
+ throw new InvalidOperationException($"Unexpected result type: {this.GetType().Name}");
}
Suggestion importance[1-10]: 6
PR 15467 (2025-03-21) |
[general] Improve error message clarity
✅ Improve error message clarity
The error message should be more specific about the expected types. Currently it mentions "PartitionDescriptor" which is a parent class, but the check is specifically for BrowsingContextPartitionDescriptor or StorageKeyPartitionDescriptor.
javascript/node/selenium-webdriver/bidi/storage.js [56-61]
if (
partition !== undefined &&
!(partition instanceof BrowsingContextPartitionDescriptor || partition instanceof StorageKeyPartitionDescriptor)
) {
- throw new Error(`Params must be an instance of PartitionDescriptor. Received:'${partition}'`)
+ throw new Error(`Params must be an instance of BrowsingContextPartitionDescriptor or StorageKeyPartitionDescriptor. Received:'${partition}'`)
}
Suggestion importance[1-10]: 5
__
Why: The suggestion improves the error message by making it more specific about the expected types (BrowsingContextPartitionDescriptor or StorageKeyPartitionDescriptor) instead of the generic parent class (PartitionDescriptor). This enhances code clarity and debugging experience.
PR 15466 (2025-03-20) |
[general] Fix incorrect docstring description
✅ Fix incorrect docstring description
The docstring for web_socket_url incorrectly states it's for accepting insecure certificates. It should describe WebSocket URL functionality instead.
py/selenium/webdriver/common/options.py [287-288]
web_socket_url = _BaseOptionsDescriptor("webSocketUrl")
-"""Gets and Set whether the session accepts insecure certificates.
+"""Gets and Sets WebSocket URL.
Suggestion importance[1-10]: 8
__
Why: The suggestion correctly identifies a significant error in the docstring where the WebSocket URL property is incorrectly described as controlling insecure certificates acceptance. This is a clear documentation bug that could mislead developers.
[general] Fix incorrect parameter type
✅ Fix incorrect parameter type
The parameter and return type for web_socket_url are incorrectly documented as bool when they should be str based on the property name and its usage.
py/selenium/webdriver/common/options.py [421-439]
web_socket_url = _BaseOptionsDescriptor("webSocketUrl")
"""Gets and Sets WebSocket URL.
Usage:
------
- Get
- `self.web_socket_url`
- Set
- `self.web_socket_url` = `value`
Parameters:
-----------
-`value`: `bool`
+`value`: `str`
Returns:
--------
- Get
- - `bool`
+ - `str`
- Set
- `None`
"""
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies that the parameter and return types for web_socket_url are incorrectly documented as boolean when they should be strings. This is an important documentation fix that prevents confusion about the expected data types.
[possible issue] Remove duplicate property declaration
✅ Remove duplicate property declaration
The web_socket_url property is duplicated in the BaseOptions class. There are two identical property declarations at lines 287 and 421, which could cause confusion or unexpected behavior.
py/selenium/webdriver/common/options.py [421-441]
-web_socket_url = _BaseOptionsDescriptor("webSocketUrl")
-"""Gets and Sets WebSocket URL.
+# Remove the duplicate declaration, keeping only one instance of web_socket_url
-Usage:
-------
-- Get
- - `self.web_socket_url`
-- Set
- - `self.web_socket_url` = `value`
-
-Parameters:
------------
-`value`: `bool`
-
-Returns:
---------
-- Get
- - `bool`
-- Set
- - `None`
-"""
-
Suggestion importance[1-10]: 9
__
Why: The suggestion correctly identifies a duplicate declaration of the web_socket_url property in the BaseOptions class. This duplication (at lines 287-305 and 421-440) could lead to unexpected behavior as the second declaration would override the first one. Removing the duplicate is critical for proper class functionality.
[general] Fix inconsistent docstring formatting
✅ Fix inconsistent docstring formatting
The indentation in the docstring is inconsistent. The "Example:" section has one less dash than the "Parameters:" section, which could cause issues with Sphinx documentation generation.
py/selenium/webdriver/remote/webdriver.py [814-824]
def set_page_load_timeout(self, time_to_wait: float) -> None:
"""Sets the amount of time to wait for a page load to complete before
throwing an error.
Parameters:
-----------
time_to_wait : float
- The amount of time to wait (in seconds)
Example:
- -------
+ --------
>>> driver.set_page_load_timeout(30)
"""
Suggestion importance[1-10]: 5
__
Why: The suggestion correctly identifies an inconsistency in the docstring formatting where the "Example:" section uses 7 dashes (-------) while the "Parameters:" section uses 9 dashes (-----------). This inconsistency could affect documentation generation with tools like Sphinx.
PR 15448 (2025-03-18) |
[general] Initialize registration state field
✅ Initialize registration state field
Initialize the registered field to false in the constructor to ensure it has a proper default value. Currently, it's declared but not initialized, which could lead to unexpected behavior.
java/src/org/openqa/selenium/grid/node/Node.java [134-138]
protected boolean registered;
protected Node(
Tracer tracer, NodeId id, URI uri, Secret registrationSecret, Duration sessionTimeout) {
this.tracer = Require.nonNull("Tracer", tracer);
+ this.registered = false;
Suggestion importance[1-10]: 7
__
Why: The suggestion addresses a potential issue where the new 'registered' field is declared but not initialized in the constructor. Explicitly initializing it to false ensures consistent behavior across all Node instances and prevents potential bugs from uninitialized state.
PR 15426 (2025-03-15) |
[possible issue] Handle potential null string
✅ Handle potential null string
The RemoteValue.String() method is called with a potentially null string value from GetString(), but the method doesn't appear to handle null values properly. This could lead to a NullReferenceException.
dotnet/src/webdriver/BiDi/Communication/Json/Converters/Polymorphic/RemoteValueConverter.cs [36]
-return RemoteValue.String(jsonDocument.RootElement.GetString());
+return RemoteValue.String(jsonDocument.RootElement.GetString() ?? string.Empty);
Suggestion importance[1-10]: 7
__
Why: The suggestion addresses a potential NullReferenceException by handling the case where GetString() returns null. This is a valid defensive programming practice that improves code robustness.
PR 15416 (2025-03-13) |
[possible issue] Fix DevTools connections closure
✅ Fix DevTools connections closure
The current implementation of the quit method might not properly close all DevTools connections if @devtools is initialized but empty. Use each instead of map to ensure proper closure of all connections.
rb/lib/selenium/webdriver/common/driver.rb [187-192]
def quit
bridge.quit
ensure
@service_manager&.stop
- @devtools&.values&.map(&:close)
+ @devtools&.values&.each(&:close) if @devtools
end
Suggestion importance[1-10]: 7
__
Why: The suggestion improves error handling by ensuring DevTools connections are properly closed even if @devtools is initialized but empty. Using each
instead of map
is more appropriate since we're not collecting return values, and adding the if @devtools
check provides additional safety.
PR 15395 (2025-03-09) |
[possible issue] Fix boolean assertion logic
✅ Fix boolean assertion logic
The JavaScript assertion for Boolean values is incorrect. The typeof operator returns the string "boolean" for boolean values, and you're comparing it directly to true/false. You should either remove the typeof or change the assertion to check the value directly.
dotnet/test/common/BiDi/Script/CallFunctionParameterTest.cs [275-282]
-//yield return new TestCaseData(new LocalValue.Boolean(true), new RemoteValue.Boolean(true), "typeof arg === true")
+//yield return new TestCaseData(new LocalValue.Boolean(true), new RemoteValue.Boolean(true), "arg === true")
//{
// TestName = nameof(CanCallFunctionAndRoundtrip_Five) + "(true)",
//};
-//yield return new TestCaseData(new LocalValue.Boolean(false), new RemoteValue.Boolean(false), "typeof arg === false")
+//yield return new TestCaseData(new LocalValue.Boolean(false), new RemoteValue.Boolean(false), "arg === false")
//{
// TestName = nameof(CanCallFunctionAndRoundtrip_Five) + "(false)",
//};
Suggestion importance[1-10]: 8
__
Why: The suggestion correctly identifies a logical error in the commented-out test cases. The JavaScript assertion "typeof arg === true" is incorrect as typeof would return the string "boolean", not the boolean value itself. This would cause the tests to fail if uncommented.
PR 15392 (2025-03-08) |
[general] Add Async suffix
✅ Add Async suffix
The method should be named with the "Async" suffix to follow the async method naming convention, as it returns a Task and calls an async method.
dotnet/src/webdriver/BiDi/Modules/BrowsingContext/BrowsingContextInputModule.cs [38-41]
-public Task SetFiles(Script.ISharedReference element, IEnumerable<string> files, SetFilesOptions? options = null)
+public Task SetFilesAsync(Script.ISharedReference element, IEnumerable<string> files, SetFilesOptions? options = null)
{
return inputModule.SetFilesAsync(context, element, files, options);
}
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies an inconsistency in method naming conventions. Methods that return Task should have the "Async" suffix according to C# conventions, especially since the method it calls (SetFilesAsync) follows this pattern. This improves code consistency and readability.
PR 15379 (2025-03-05) |
[general] Add missing sealed modifier
✅ Add missing sealed modifier
The class should be explicitly marked as sealed since the implementation now prevents inheritance by removing the protected constructor and making all constructors private.
dotnet/src/webdriver/RelativeBy.cs [32-36]
-public class RelativeBy : By
+public sealed class RelativeBy : By
{
private readonly string wrappedAtom;
private readonly object root;
private readonly List<object> filters;
Suggestion importance[1-10]: 7
__
Why: The suggestion correctly identifies that the class should be marked as sealed since the implementation prevents inheritance by removing the protected constructor and making all constructors private. This improves code clarity and prevents potential misuse.
[learned best practice] Use explicit collection initialization with new List() instead of collection expressions for better readability and consistency with .NET conventions
✅ Use explicit collection initialization with new List() instead of collection expressions for better readability and consistency with .NET conventions
The current implementation uses collection expressions [] to initialize an empty list when filters is null. While this works, it's better to use new List() or the collection initializer syntax new() for consistency with .NET conventions and to make the code more explicit about the type being created.
dotnet/src/webdriver/RelativeBy.cs [56]
-this.filters = filters is null ? [] : [.. filters]; // Clone filters
+this.filters = filters is null ? new List<object>() : new List<object>(filters); // Clone filters
Suggestion importance[1-10]: 6
PR 15354 (2025-03-01) |
[general] Unify nullable reference type settings
✅ Unify nullable reference type settings
Consider using a single Nullable property setting for all target frameworks to maintain consistent null-checking behavior across the codebase.
dotnet/src/webdriver/WebDriver.csproj [45-54]
-<PropertyGroup Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net8.0'))">
+<PropertyGroup>
<Nullable>enable</Nullable>
<!--TODO when AOT is ready https://github.com/SeleniumHQ/selenium/issues/14480-->
<!--<IsAotCompatible>true</IsAotCompatible>-->
</PropertyGroup>
-<PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard2.0'">
- <Nullable>annotations</Nullable>
-</PropertyGroup>
-
Suggestion importance[1-10]: 2
__
Why: While the suggestion to unify nullable settings is technically valid, having different nullable settings for different target frameworks is intentional here, as netstandard2.0 may have compatibility constraints that make full nullable enforcement impractical. The current approach is more nuanced and appropriate.
[general] Standardize nullable settings across targets
✅ Standardize nullable settings across targets
Consider using consistent nullable settings across all library targets. Currently mixing "enable" and "annotations" which could lead to inconsistent null checking behavior.
dotnet/src/webdriver/BUILD.bazel [40-146]
-+ nullable="annotations"
++ nullable="enable"
...
+ nullable="enable"
Suggestion importance[1-10]: 2
__
Why: The suggestion to standardize nullable settings to "enable" across all targets is incorrect. The PR intentionally uses different nullable settings ("annotations" for netstandard2.0 and "enable" for net8.0) to match the configuration in WebDriver.csproj, which shows this is a deliberate design choice.
PR 15348 (2025-02-28) |
[general] Enhance logging with session ID
Enhance logging with session ID
Add missing session ID to the drain event message to improve traceability and debugging.
java/src/org/openqa/selenium/grid/node/local/LocalNode.java [1070-1071]
span.addEvent(
- String.format("%s session(s) pending before draining Node", currentSessionCount));
+ String.format("%s session(s) pending before draining Node %s", currentSessionCount, getId()));
Suggestion importance[1-10]: 5
__
Why: Adding the node ID to the drain event message improves observability and debugging capabilities by making it easier to track which node is being drained. This is a useful enhancement for system monitoring.
PR 15283 (2025-02-13) |
[possible issue] Add null check for handler
✅ Add null check for handler
Add null check for the returned HttpClientHandler from CreateHttpClientHandler() before using it to avoid potential NullReferenceException
dotnet/src/webdriver/Remote/HttpCommandExecutor.cs [248-252]
protected virtual HttpClient CreateHttpClient()
{
var httpClientHandler = CreateHttpClientHandler();
+ if (httpClientHandler == null)
+ {
+ throw new InvalidOperationException("CreateHttpClientHandler() returned null");
+ }
HttpMessageHandler handler = httpClientHandler;
Suggestion importance[1-10]: 8
__
Why: The suggestion addresses a potential null reference exception that could occur if CreateHttpClientHandler() returns null. This is a critical defensive programming practice for virtual methods that can be overridden by derived classes.
[learned best practice] Add null validation check for required class field to prevent potential NullReferenceException
✅ Add null validation check for required class field to prevent potential NullReferenceException
The CreateHttpClientHandler() method uses this.remoteServerUri without validating that it's not null. Since this is a required field for the class functionality, add a null check at the start of the method to fail fast with a clear error message.
dotnet/src/webdriver/Remote/HttpCommandExecutor.cs [229-233]
protected virtual HttpClientHandler CreateHttpClientHandler()
{
+ ArgumentNullException.ThrowIfNull(this.remoteServerUri, nameof(remoteServerUri));
HttpClientHandler httpClientHandler = new HttpClientHandler();
string userInfo = this.remoteServerUri.UserInfo;
if (!string.IsNullOrEmpty(userInfo) && userInfo.Contains(":"))
Suggestion importance[1-10]: 6
PR 15258 (2025-02-09) |
[possible issue] Initialize collection to prevent nulls
✅ Initialize collection to prevent nulls
Initialize the Headers dictionary in the parameterless constructor to prevent NullReferenceException when adding headers.
dotnet/src/webdriver/HttpRequestData.cs [34-39]
public HttpRequestData()
{
this.Method = null!;
this.Url = null!;
- this.Headers = null!;
+ this.Headers = new Dictionary<string, string>();
}
Suggestion importance[1-10]: 8
__
Why: Initializing Headers with null! could lead to NullReferenceException at runtime. Using a new Dictionary instance is a safer approach that prevents potential crashes.
[general] Use meaningful defaults over nulls
✅ Use meaningful defaults over nulls
Avoid using null-forgiving operator (!) for required properties. Instead, initialize with meaningful default values.
dotnet/src/webdriver/HttpRequestData.cs [34-39]
public HttpRequestData()
{
- this.Method = null!;
- this.Url = null!;
- this.Headers = null!;
+ this.Method = "GET";
+ this.Url = string.Empty;
+ this.Headers = new Dictionary<string, string>();
}
Suggestion importance[1-10]: 7
__
Why: Using meaningful default values instead of null-forgiving operators improves code safety and clarity. The suggestion provides sensible defaults that better represent the initial state of an HTTP request.
PR 15257 (2025-02-09) |
[possible issue] Add null checks for nullable delegates
✅ Add null checks for nullable delegates
The FindElementMethod and FindElementsMethod properties are marked as nullable but used without null checks in FindElement and FindElements methods. Add null checks to prevent potential NullReferenceException.
dotnet/src/webdriver/By.cs [332-333]
public virtual IWebElement FindElement(ISearchContext context)
{
+ if (this.FindElementMethod == null)
+ {
+ throw new InvalidOperationException("FindElementMethod not set");
+ }
return this.FindElementMethod(context);
}
Suggestion importance[1-10]: 9
__
Why: The suggestion addresses a critical potential NullReferenceException by adding necessary null checks for nullable delegate properties that are used directly. This is especially important since the code has #nullable enable.
[possible issue] Avoid null reference runtime exceptions
✅ Avoid null reference runtime exceptions
Initialize RequestMatcher in the constructor instead of using null! to avoid potential null reference exceptions at runtime.
dotnet/src/webdriver/NetworkRequestHandler.cs [35]
-public Func<HttpRequestData, bool> RequestMatcher { get; set; } = null!;
+public Func<HttpRequestData, bool> RequestMatcher { get; set; } = _ => false;
Suggestion importance[1-10]: 8
__
Why: The suggestion provides a safer default implementation that prevents null reference exceptions at runtime, which is a critical improvement over using null! that could lead to runtime crashes.
[possible issue] Provide safe default function implementations
✅ Provide safe default function implementations
Initialize ResponseMatcher and ResponseTransformer in the constructor with safe default implementations instead of using null! to avoid potential null reference exceptions.
dotnet/src/webdriver/NetworkResponseHandler.cs [35-42]
-public Func<HttpResponseData, bool> ResponseMatcher { get; set; } = null!;
-public Func<HttpResponseData, HttpResponseData> ResponseTransformer { get; set; } = null!;
+public Func<HttpResponseData, bool> ResponseMatcher { get; set; } = _ => false;
+public Func<HttpResponseData, HttpResponseData> ResponseTransformer { get; set; } = response => response;
Suggestion importance[1-10]: 8
__
Why: The suggestion replaces potentially dangerous null! assignments with safe default implementations for both ResponseMatcher and ResponseTransformer, preventing runtime exceptions and providing sensible default behavior.
[possible issue] Add safe default function implementation
✅ Add safe default function implementation
Initialize UriMatcher with a safe default implementation instead of using null! to avoid potential null reference exceptions.
dotnet/src/webdriver/NetworkAuthenticationHandler.cs [35]
-public Func<Uri, bool> UriMatcher { get; set; } = null!;
+public Func<Uri, bool> UriMatcher { get; set; } = _ => false;
Suggestion importance[1-10]: 8
__
Why: The suggestion replaces the null! assignment with a safe default implementation for UriMatcher, preventing potential null reference exceptions and providing a reasonable default behavior.
[learned best practice] Add null validation checks for nullable delegate properties before invoking them to prevent NullReferenceExceptions
✅ Add null validation checks for nullable delegate properties before invoking them to prevent NullReferenceExceptions
The FindElement and FindElements methods should validate that their FindElementMethod and FindElementsMethod properties are not null before using them, since they are marked as nullable. Add ArgumentNullException checks at the start of these methods.
dotnet/src/webdriver/By.cs [330-344]
public virtual IWebElement FindElement(ISearchContext context)
{
+ ArgumentNullException.ThrowIfNull(this.FindElementMethod, nameof(FindElementMethod));
return this.FindElementMethod(context);
}
-public virtual ReadOnlyCollection<IWebElement> FindElements(ISearchContext context)
+public virtual ReadOnlyCollection<IWebElement> FindElements(ISearchContext context)
{
+ ArgumentNullException.ThrowIfNull(this.FindElementsMethod, nameof(FindElementsMethod));
return this.FindElementsMethod(context);
}
PR 15251 (2025-02-07) |
[possible issue] Add parameter validation
✅ Add parameter validation
Add null checks for the subscription ID and event handler parameters to prevent potential NullReferenceException when unsubscribing.
dotnet/src/webdriver/BiDi/Communication/Broker.cs [274-281]
public async Task UnsubscribeAsync(Modules.Session.Subscription subscription, EventHandler eventHandler)
{
+ ArgumentNullException.ThrowIfNull(subscription);
+ ArgumentNullException.ThrowIfNull(eventHandler);
+
var eventHandlers = _eventHandlers[eventHandler.EventName];
eventHandlers.Remove(eventHandler);
await _bidi.SessionModule.UnsubscribeAsync([subscription]).ConfigureAwait(false);
}
Suggestion importance[1-10]: 8
__
Why: Adding null checks for parameters is crucial for preventing runtime NullReferenceExceptions, especially in an async method that handles critical subscription management.
PR 15243 (2025-02-05) |
[general] Improve error message clarity
✅ Improve error message clarity
Add a more descriptive error message that includes the context of why the value was expected to be non-null, to help with debugging.
dotnet/src/webdriver/Response.cs [225]
-return Value ?? throw new WebDriverException("Expected not-null response");
+return Value ?? throw new WebDriverException("Response.Value was null when a non-null value was expected");
Suggestion importance[1-10]: 6
__
Why: The improved error message provides more context about which property was null, making it easier to diagnose issues. While helpful, this is a minor improvement to error handling.
PR 15241 (2025-02-05) |
[possible issue] Validate JSON property existence
✅ Validate JSON property existence
Add null check for the 'clientWindows' property existence in JSON to prevent potential JsonException
-var clientWindows = doc.RootElement.GetProperty("clientWindows").Deserialize<IReadOnlyList<ClientWindowInfo>>(options);
+if (!doc.RootElement.TryGetProperty("clientWindows", out JsonElement clientWindowsElement))
+ throw new JsonException("Missing required 'clientWindows' property");
+var clientWindows = clientWindowsElement.Deserialize<IReadOnlyList<ClientWindowInfo>>(options);
Suggestion importance[1-10]: 8
__
Why: The suggestion adds crucial error handling to validate JSON structure before deserialization, preventing potential runtime exceptions and providing clearer error messages.
PR 15236 (2025-02-05) |
[possible issue] Add null check for response value
✅ Add null check for response value
Add null check for response.Value in GetContext() method before attempting ToString() conversion to avoid potential NullReferenceException.
dotnet/src/webdriver/Firefox/FirefoxDriver.cs [263-266]
Response commandResponse = this.Execute(GetContextCommand, null);
-if (commandResponse.Value is not string response
+if (commandResponse.Value is null
+ || commandResponse.Value is not string response
|| !Enum.TryParse(response, ignoreCase: true, out FirefoxCommandContext output))
Suggestion importance[1-10]: 8
__
Why: The suggestion adds an important null check for commandResponse.Value before attempting to use it, which prevents potential NullReferenceException. This is a critical defensive programming practice when dealing with response values.
PR 15232 (2025-02-04) |
[possible issue] Prevent null reference exception
✅ Prevent null reference exception
Add null check for binaryPaths.BrowserPath before validating file existence to prevent NullReferenceException. The browser path might be null in some cases.
dotnet/src/webdriver/DriverFinder.cs [119-122]
-if (!File.Exists(binaryPaths.BrowserPath))
+if (!string.IsNullOrEmpty(binaryPaths.BrowserPath) && !File.Exists(binaryPaths.BrowserPath))
{
throw new NoSuchDriverException($"The browser path is not a valid file: {binaryPaths.BrowserPath}");
}
Suggestion importance[1-10]: 8
Why: The suggestion addresses a critical null reference safety issue that could cause runtime crashes. The browser path validation should indeed check for null/empty values before attempting to verify file existence.
[possible issue] Handle null browser path safely
✅ Handle null browser path safely
Add null check for path before accessing it in GetBrowserPath() to prevent potential NullReferenceException when accessing BrowserPath property.
dotnet/src/webdriver/DriverFinder.cs [56-59]
public string GetBrowserPath()
{
- return BinaryPaths().BrowserPath;
+ var paths = BinaryPaths();
+ return paths.BrowserPath ?? string.Empty;
}
Suggestion importance[1-10]: 7
Why: The suggestion improves null safety by handling potential null browser paths gracefully, preventing runtime exceptions. This is particularly important as the code already shows signs of null-safety concerns with nullable annotations.
PR 15230 (2025-02-04) |
[possible issue] Handle null response values
✅ Handle null response values
Add null check for commandResponse.Value before calling ToString() since the response value could be null, which would cause a NullReferenceException
dotnet/src/webdriver/WebElement.cs [100-102]
Response commandResponse = this.Execute(DriverCommand.GetElementText, parameters);
-return commandResponse.Value.ToString();
+return commandResponse.Value?.ToString() ?? string.Empty;
Suggestion importance[1-10]: 8
Why: The suggestion addresses a potential NullReferenceException by safely handling null response values, which is critical for robust error handling and preventing runtime crashes.
[learned best practice] Add null validation checks for nullable parameters at the start of methods to prevent NullReferenceExceptions
✅ Add null validation checks for nullable parameters at the start of methods to prevent NullReferenceExceptions
Add ArgumentNullException.ThrowIfNull() checks for nullable parameters 'attributeName', 'propertyName', and 'text' at the start of GetAttribute(), GetDomAttribute(), GetDomProperty(), GetCssValue() and SendKeys() methods to prevent potential NullReferenceExceptions.
dotnet/src/webdriver/WebElement.cs [445-452]
public virtual string? GetAttribute(string attributeName)
{
+ ArgumentNullException.ThrowIfNull(attributeName, nameof(attributeName));
+
Dictionary<string, object> parameters = new Dictionary<string, object>();
string atom = GetAtom("get-attribute.js");
parameters.Add("script", atom);
parameters.Add("args", new object[] { ((IWebDriverObjectReference)this).ToDictionary(), attributeName });
PR 15228 (2025-02-04) |
[possible issue] Add null checks for response
✅ Add null checks for response
The PageSource property should handle null responses from Execute() to prevent potential NullReferenceException when accessing Value property.
dotnet/src/webdriver/WebDriver.cs [133-140]
public string PageSource
{
get
{
Response commandResponse = this.Execute(DriverCommand.GetPageSource, null);
-
- return commandResponse.Value.ToString();
+ return commandResponse?.Value?.ToString() ?? string.Empty;
}
}
Suggestion importance[1-10]: 8
Why: The suggestion prevents potential NullReferenceException by adding proper null checks when accessing response values. This is an important defensive programming fix for a real potential bug.
[possible issue] Add null check for handles array
✅ Add null check for handles array
The WindowHandles property should validate that handles is not null before attempting to create a new List with its length to prevent potential NullReferenceException.
dotnet/src/webdriver/WebDriver.cs [165-166]
-object[] handles = (object[])commandResponse.Value;
+object[] handles = (object[])commandResponse.Value ?? Array.Empty<object>();
List<string> handleList = new List<string>(handles.Length);
Suggestion importance[1-10]: 7
Why: The suggestion prevents a potential NullReferenceException by providing a fallback empty array when the response value is null. This is an important defensive programming improvement.
[possible issue] Fix incorrect null check
✅ Fix incorrect null check
The GetElementFromResponse method should throw NoSuchElementException when response.Value is null, not when response itself is null. The current implementation could mask underlying issues.
dotnet/src/webdriver/WebDriver.cs [524-527]
-if (response == null)
+if (response?.Value == null)
{
throw new NoSuchElementException();
}
Suggestion importance[1-10]: 8
Why: The suggestion fixes a potential bug where null response values would not be properly handled, which could mask underlying issues and cause incorrect error reporting.
[possible issue] Prevent potential null reference
✅ Prevent potential null reference
The Title property should check if commandResponse is null before using the null-coalescing operator on its Value property to avoid potential NullReferenceException.
dotnet/src/webdriver/WebDriver.cs [123]
-object returnedTitle = commandResponse?.Value ?? string.Empty;
+object returnedTitle = commandResponse == null ? string.Empty : commandResponse.Value ?? string.Empty;
Suggestion importance[1-10]: 7
Why: The suggestion adds important null safety checks to prevent NullReferenceException when commandResponse is null, improving the robustness of the code.
PR 15220 (2025-02-03) |
[possible issue] Add null check for path
✅ Add null check for path
Add null check for Path.GetDirectoryName() result since it can return null for invalid paths. The current forced null-forgiving operator (!) could lead to NullReferenceException.
dotnet/src/webdriver/Firefox/FirefoxDriverService.cs [203]
-driverPath = Path.GetDirectoryName(driverPath)!;
+var dirPath = Path.GetDirectoryName(driverPath);
+if (dirPath == null) throw new ArgumentException("Invalid driver path provided", nameof(driverPath));
+driverPath = dirPath;
- Apply this suggestion Suggestion importance[1-10]: 8
Why: The suggestion addresses a potential null reference exception by properly handling the case where Path.GetDirectoryName returns null, which is a critical safety check for path operations.
PR 15217 (2025-02-02) |
[learned best practice] Use modern C# pattern matching instead of explicit null checks when checking interface implementation
✅ Use modern C# pattern matching instead of explicit null checks when checking interface implementation
While the PR introduces the null-coalescing assignment (??=) operator for the Network property, the null check for ISupportsLogs interface could be simplified using the is pattern matching operator for more concise and modern C# code.
dotnet/src/webdriver/WebDriver.cs [81]
-if ((this as ISupportsLogs) != null)
+if (this is ISupportsLogs)
{
PR 15202 (2025-01-31) |
[possible issue] Add type constraint for safety
✅ Add type constraint for safety
The generic SendAsJsonAsync method should include a constraint to ensure T is a Command type to maintain type safety and prevent invalid command objects from being sent.
dotnet/src/webdriver/BiDi/Communication/Transport/ITransport.cs [35]
-Task SendAsJsonAsync<T>(T command, JsonSerializerContext jsonSerializerContext, CancellationToken cancellationToken);
+Task SendAsJsonAsync<T>(T command, JsonSerializerContext jsonSerializerContext, CancellationToken cancellationToken) where T : Command;
- Apply this suggestion Suggestion importance[1-10]: 8
Why: Adding a type constraint to ensure T is a Command type is a critical safety improvement that prevents runtime errors by enforcing proper type checking at compile time. This is especially important as the PR changes the signature from a concrete Command type to a generic T.
PR 15180 (2025-01-28) |
[possible issue] Add missing base class inheritance
✅ Add missing base class inheritance
The generated JSON serialization context class should inherit from JsonSerializerContext to enable proper JSON serialization functionality.
third_party/dotnet/devtools/src/generator/Templates/DevToolsSessionDomains.hbs [51]
-internal sealed partial class {{protocolVersion}}JsonSerializationContext;
+internal sealed partial class {{protocolVersion}}JsonSerializationContext : JsonSerializerContext;
- Apply this suggestion Suggestion importance[1-10]: 10
Why: The suggestion fixes a critical issue by adding the required base class inheritance, which is essential for the JSON serialization context to function properly. This matches the implementation in the individual version files.
PR 15179 (2025-01-28) |
[possible issue] Fix incorrect session validation logic
✅ Fix incorrect session validation logic
The session validation logic in useEffect has incorrect condition. The current condition (sessionId !== undefined || sessionId === '') will always be true, potentially causing unnecessary navigations.
javascript/grid-ui/src/screens/Sessions/Sessions.tsx [44-46]
-if ((sessionId !== undefined || sessionId === '') && data.sessionsInfo.sessions.length === 0) {
+if (sessionId && data.sessionsInfo.sessions.length === 0) {
navigate("/sessions")
}
- Apply this suggestion Suggestion importance[1-10]: 9
Why: The current condition has a logical error that would always evaluate to true, causing unnecessary navigations. This fix is critical for proper session validation and routing behavior.
PR 15170 (2025-01-27) |
[possible issue] Add null check for capability
✅ Add null check for capability
Add null check for 'webSocketUrl' capability to prevent NullPointerException when casting to Boolean
java/src/org/openqa/selenium/devtools/CdpEndpointFinder.java [94]
-if (!(Boolean) caps.getCapability("webSocketUrl")) {
+if (caps.getCapability("webSocketUrl") == null || !(Boolean) caps.getCapability("webSocketUrl")) {
- Apply this suggestion Suggestion importance[1-10]: 9
Why: The suggestion addresses a critical potential NullPointerException that could occur when casting a null capability value to Boolean. This is a significant safety improvement that prevents runtime crashes.
PR 15163 (2025-01-26) |
[possible issue] Add null parameter validation
✅ Add null parameter validation
Add null check for webDriver parameter to prevent NullReferenceException when calling the extension method with null
dotnet/src/webdriver/BiDi/WebDriver.Extensions.cs [29-31]
public static async Task<BiDi> AsBiDiAsync(this IWebDriver webDriver)
{
+ ArgumentNullException.ThrowIfNull(webDriver);
var webSocketUrl = ((IHasCapabilities)webDriver).Capabilities.GetCapability("webSocketUrl");
- Apply this suggestion Suggestion importance[1-10]: 8
Why: Adding null parameter validation is crucial for preventing NullReferenceException and providing better error handling. This is a significant defensive programming practice that improves code robustness and provides clearer error messages.
[learned best practice] Add proper validation for nullable values before using them to prevent potential runtime errors
✅ Add proper validation for nullable values before using them to prevent potential runtime errors
The code uses null-forgiving operator (!) on webSocketUrl.ToString() which could lead to runtime errors if webSocketUrl is null. Instead, validate the value before using it and provide a clear error message.
dotnet/src/webdriver/BiDi/WebDriver.Extensions.cs [33-35]
-if (webSocketUrl is null) throw new BiDiException("The driver is not compatible with bidirectional protocol or \"webSocketUrl\" not enabled in driver options.");
-var bidi = await BiDi.ConnectAsync(webSocketUrl.ToString()!).ConfigureAwait(false);
+if (webSocketUrl is null)
+ throw new BiDiException("The driver is not compatible with bidirectional protocol or \"webSocketUrl\" not enabled in driver options.");
+var webSocketUrlStr = webSocketUrl.ToString();
+if (string.IsNullOrEmpty(webSocketUrlStr))
+ throw new BiDiException("Invalid empty webSocketUrl value");
+
+var bidi = await BiDi.ConnectAsync(webSocketUrlStr).ConfigureAwait(false);
+
- Apply this suggestion
PR 15147 (2025-01-24) |
[possible issue] Fix parameters initialization logic
✅ Fix parameters initialization logic
The constructor assigns parameters directly to Parameters property only when not null, but the property already initializes a new dictionary. This can lead to inconsistent state. Consider removing the default initialization.
dotnet/src/webdriver/Command.cs [85]
-public Dictionary<string, object> Parameters { get; } = new Dictionary<string, object>();
+public Dictionary<string, object> Parameters { get; private set; } = new();
- Apply this suggestion Suggestion importance[1-10]: 7
Why: The suggestion correctly identifies a potential state inconsistency issue where the Parameters property has both an initializer and conditional assignment in the constructor, which could lead to confusion and bugs.
PR 15144 (2025-01-24) |
[possible issue] Fix constructor initialization pattern
✅ Fix constructor initialization pattern
The constructor is not properly initializing the page size. The property pageSize should be set directly instead of using PageDimensions to avoid potential null checks and exceptions.
dotnet/src/webdriver/PrintOptions.cs [66-69]
public PrintOptions()
{
- this.PageDimensions = A4; // Default to A4 page size
+ this.pageSize = A4; // Default to A4 page size
}
- Apply this suggestion Suggestion importance[1-10]: 8
Why: The suggestion correctly identifies a potential issue where using PageDimensions setter could throw an exception during object construction. Direct field initialization is safer and more appropriate for constructors.
[general] Remove redundant null validation
✅ Remove redundant null validation
The SetPageSize method duplicates the null check that's already present in the PageDimensions property. Remove the redundant validation to maintain DRY principles.
dotnet/src/webdriver/PrintOptions.cs [120-127]
public void SetPageSize(PageSize pageSize)
{
- if (pageSize == null)
- {
- throw new ArgumentNullException(nameof(pageSize), "Page size cannot be null.");
- }
this.PageDimensions = pageSize;
}
- Apply this suggestion Suggestion importance[1-10]: 5
Why: The suggestion correctly points out code duplication in null validation, as PageDimensions property already handles null checks. While valid, the impact is mainly on code maintainability rather than functionality.
PR 15143 (2025-01-23) |
[possible issue] Add null check for domain type
✅ Add null check for domain type
Add null check for domainType before accessing its constructor to prevent potential NullReferenceException if no matching domain type is found.
dotnet/src/webdriver/DevTools/DevToolsDomains.cs [100-101]
+if (domainType == null)
+ throw new ArgumentException("No matching domain type found for the specified version");
ConstructorInfo constructor = domainType.GetConstructor(new Type[] { typeof(DevToolsSession) })!;
return (DevToolsDomains)constructor.Invoke(new object[] { session });
- Apply this suggestion Suggestion importance[1-10]: 8
Why: The suggestion addresses a critical potential null reference exception that could occur if no matching domain type is found, improving the robustness of the code.
PR 15136 (2025-01-23) |
[possible issue] Validate array input parameters
✅ Validate array input parameters
Add input validation for contexts array to ensure it contains only valid, non-empty strings when provided
javascript/node/selenium-webdriver/bidi/network.js [378-380]
if (contexts) {
+ if (!Array.isArray(contexts) || contexts.some(c => !c || typeof c !== 'string')) {
+ throw new Error('Contexts must be an array of non-empty strings')
+ }
command.params.contexts = contexts
}
Suggestion importance[1-10]: 8
Why: Adding validation for the contexts parameter is important for preventing runtime errors and ensuring data integrity. The suggestion adds proper type checking and validation that was missing from the original implementation.
[general] Add missing error test case
✅ Add missing error test case
Add test case to verify error handling when contexts parameter contains invalid values
javascript/node/selenium-webdriver/test/bidi/network_test.js [240-246]
it('throws error for invalid cache behavior', async function () {
await driver.get(Pages.emptyPage)
await assert.rejects(
async () => await network.setCacheBehavior('invalid'),
/Cache behavior must be either "default" or "bypass"/,
)
+ await assert.rejects(
+ async () => await network.setCacheBehavior('default', [null, 123, '']),
+ /Contexts must be an array of non-empty strings/,
+ )
})
Suggestion importance[1-10]: 7
Why: The suggestion improves test coverage by adding validation for invalid contexts parameter, which complements the first suggestion and helps ensure the error handling works correctly.
PR 15135 (2025-01-23) |
[possible issue] Fix premature exception for hidden options
✅ Fix premature exception for hidden options
The current implementation raises NoSuchElementException too early in the loop, preventing checking of other matching options that might be visible. Move the visibility check after examining all options.
py/selenium/webdriver/support/select.py [116-119]
-for opt in opts:
- if not self._has_css_property_and_visible(opt):
- raise NoSuchElementException(f"Could not locate element with visible text: {text}")
+visible_opts = [opt for opt in opts if self._has_css_property_and_visible(opt)]
+if not visible_opts:
+ raise NoSuchElementException(f"Could not locate element with visible text: {text}")
+for opt in visible_opts:
self._set_selected(opt)
Suggestion importance[1-10]: 9
Why: The current implementation incorrectly raises an exception on the first hidden option, potentially missing visible options that match the text. The suggested change correctly checks all options before raising the exception.
PR 15130 (2025-01-22) |
[general] Optimize map creation efficiency
✅ Optimize map creation efficiency
The toMap() method creates new Map instances unnecessarily. Optimize by using a single mutable map and conditionally adding the contexts.
java/src/org/openqa/selenium/bidi/network/SetCacheBehaviorParameters.java [37-45]
public Map<String, Object> toMap() {
- Map<String, Object> map = Map.of("cacheBehavior", cacheBehavior.toString());
-
+ Map<String, Object> map = new HashMap<>();
+ map.put("cacheBehavior", cacheBehavior.toString());
+
if (contexts != null && !contexts.isEmpty()) {
- return Map.of("cacheBehavior", cacheBehavior.toString(), "contexts", contexts);
+ map.put("contexts", contexts);
}
-
+
return map;
}
- Apply this suggestion Suggestion importance[1-10]: 6
Why: The suggestion improves code efficiency by replacing immutable Map.of() calls with a single mutable HashMap, reducing object creation overhead and making the code more maintainable. While valid, this is a minor optimization with moderate impact.
PR 15110 (2025-01-17) |
[possible issue] Properly dispose of HTTP client resources to prevent memory leaks
✅ Properly dispose of HTTP client resources to prevent memory leaks
Dispose of the HttpClient instance in the Dispose method to prevent resource leaks. The current implementation might leave the HttpClient hanging.
dotnet/src/webdriver/Remote/HttpCommandExecutor.cs [52]
private HttpClient? client;
+public void Dispose()
+{
+ if (!isDisposed)
+ {
+ client?.Dispose();
+ client = null;
+ isDisposed = true;
+ }
+}
+
- Apply this suggestion Suggestion importance[1-10]: 9
Why: The suggestion addresses a critical resource management issue by ensuring proper disposal of HttpClient instances. Not disposing of HttpClient can lead to memory leaks and socket exhaustion in long-running applications.
PR 15107 (2025-01-17) |
[general] Replace direct property modification with creation of new immutable instance to maintain object immutability
✅ Replace direct property modification with creation of new immutable instance to maintain object immutability
Instead of using the deprecated Value setter, create a new Response instance with the modified value to maintain immutability principles.
dotnet/src/webdriver/Remote/HttpCommandExecutor.cs [344]
-response.Value = valueString.Replace("\r\n", "\n").Replace("\n", Environment.NewLine);
+response = new Response(response.SessionId, valueString.Replace("\r\n", "\n").Replace("\n", Environment.NewLine), response.Status);
- Apply this suggestion Suggestion importance[1-10]: 8
Why: The suggestion provides a better approach to handle the deprecated Value setter by creating a new immutable Response instance, which aligns with the PR's goal of making Response immutable. This is a significant improvement in terms of design and future compatibility.
PR 15092 (2025-01-15) |
[possible issue] Add defensive null check to prevent potential NullPointerException
✅ Add defensive null check to prevent potential NullPointerException
Add null check before string validation to prevent NullPointerException if null name is passed.
java/src/org/openqa/selenium/remote/RemoteWebDriver.java [872-874]
-if (name.isEmpty() || name.equals(" ")) {
+if (name == null || name.isEmpty() || name.equals(" ")) {
throw new IllegalArgumentException("Cookie name cannot be empty or null");
}
Suggestion importance[1-10]: 9
Why: Adding a null check is crucial to prevent NullPointerException, which could crash the application. This is a critical defensive programming practice for public methods.
[general] Improve whitespace validation by using a more comprehensive string validation method
✅ Improve whitespace validation by using a more comprehensive string validation method
Use String.isBlank() method instead of checking for empty string and single space separately. This will handle all whitespace variations more robustly.
java/src/org/openqa/selenium/remote/RemoteWebDriver.java [872-874]
-if (name.isEmpty() || name.equals(" ")) {
- throw new IllegalArgumentException("Cookie name cannot be empty or null");
+if (name == null || name.isBlank()) {
+ throw new IllegalArgumentException("Cookie name cannot be empty, null or whitespace");
}
Suggestion importance[1-10]: 7
Why: Using String.isBlank() is a more robust solution as it handles all types of whitespace characters, not just empty string and single space. This improves code reliability and maintainability.
PR 15074 (2025-01-13) |
[general] Enhance error messages with actual values for better debugging experience
✅ Enhance error messages with actual values for better debugging experience
Include the actual value in the exception message to help with debugging when an invalid cookie name is provided.
dotnet/src/webdriver/CookieJar.cs [82]
-throw new ArgumentException("Cookie name cannot be empty", nameof(name));
+throw new ArgumentException($"Cookie name cannot be empty. Provided value: '{name}'", nameof(name));
- Apply this suggestion Suggestion importance[1-10]: 4
Why: Including the actual invalid value in the exception message would help with debugging, though the current message is already clear. This is a minor improvement to developer experience.
PR 15073 (2025-01-13) |
[general] Expand test coverage to include whitespace-only input validation
✅ Expand test coverage to include whitespace-only input validation
Add test case for whitespace-only cookie names to verify they are properly rejected.
py/test/selenium/webdriver/common/cookie_tests.py [157-160]
def test_get_cookie_raises_value_error_for_empty_name(cookie, driver):
driver.add_cookie(cookie)
with pytest.raises(ValueError, match="Cookie name cannot be empty"):
driver.get_cookie("")
+ with pytest.raises(ValueError, match="Cookie name cannot be empty"):
+ driver.get_cookie(" ")
- Apply this suggestion Suggestion importance[1-10]: 8
Why: This is a valuable suggestion that improves test coverage by verifying the new whitespace validation functionality, which is a key part of the PR's changes. The test would help ensure the new validation works as intended.
PR 15065 (2025-01-12) |
[possible issue] Fix incorrect syntax in example code that would cause execution errors
✅ Fix incorrect syntax in example code that would cause execution errors
Fix the syntax error in the example code of the perform() docstring. The method call is missing parentheses and has incorrect parameter syntax.
py/selenium/webdriver/common/actions/action_builder.py [159-162]
>>> action_builder = ActionBuilder(driver)
>>> keyboard = action_builder.key_input
->>> el = driver.find_element(id: "some_id")
->>> action_builder.click(el).pause(keyboard).pause(keyboard).pause(keyboard).send_keys('keys').perform
+>>> el = driver.find_element(By.ID, "some_id")
+>>> action_builder.click(el).pause(keyboard).pause(keyboard).pause(keyboard).send_keys('keys').perform()
- Apply this suggestion Suggestion importance[1-10]: 8
Why: The suggestion fixes multiple critical syntax errors in the example code that would prevent it from running: incorrect parameter syntax for find_element(), missing parentheses in perform(), and using incorrect method chaining. These fixes are essential for the documentation to be useful.
PR 15057 (2025-01-09) |
[possible issue] Add null safety checks and proper dictionary access to prevent potential runtime exceptions
✅ Add null safety checks and proper dictionary access to prevent potential runtime exceptions
The IsEnabled method could throw a NullReferenceException if _loggers is null or if the logger's issuer type is not found in the dictionary. Add null checks and fallback logic.
dotnet/src/webdriver/Internal/Logging/LogContext.cs [104]
-return Handlers != null && level >= _level && level >= _loggers?[logger.Issuer].Level;
+return Handlers != null && level >= _level && (_loggers?.TryGetValue(logger.Issuer, out var loggerEntry) != true || level >= loggerEntry.Level);
- Apply this suggestion Suggestion importance[1-10]: 9
Why: The suggestion addresses a critical potential null reference exception in the IsEnabled method. The improved code properly handles dictionary access and null cases, which is essential for runtime stability.
[possible issue] Add null checks during dictionary initialization to prevent potential null reference exceptions
✅ Add null checks during dictionary initialization to prevent potential null reference exceptions
The logger initialization in constructor could fail if any of the source loggers has a null Issuer. Add validation to handle this case.
dotnet/src/webdriver/Internal/Logging/LogContext.cs [51]
-_loggers = new ConcurrentDictionary<Type, ILogger>(loggers.Select(l => new KeyValuePair<Type, ILogger>(l.Key, new Logger(l.Value.Issuer, level))));
+_loggers = new ConcurrentDictionary<Type, ILogger>(loggers.Where(l => l.Value?.Issuer != null).Select(l => new KeyValuePair<Type, ILogger>(l.Key, new Logger(l.Value.Issuer, level))));
- Apply this suggestion Suggestion importance[1-10]: 8
Why: The suggestion prevents potential null reference exceptions during logger initialization by adding necessary null checks. This is important for system stability and proper error handling.
PR 15008 (2025-01-02) |
[possible issue] Add proper async handling and result processing for account list retrieval
✅ Add proper async handling and result processing for account list retrieval
The accounts() method is missing the 'async' keyword and doesn't properly handle the accounts array from the result.
javascript/node/selenium-webdriver/lib/fedcm/dialog.js [44-48]
-accounts() {
- const result = this._driver.execute(new command.Command(command.Name.GET_ACCOUNTS))
- return result
+async accounts() {
+ const result = await this._driver.execute(new command.Command(command.Name.GET_ACCOUNTS))
+ return result.accounts || []
}
Suggestion importance[1-10]: 8
Why: The suggestion addresses both async handling and proper result processing, preventing potential undefined errors when no accounts are present.
[possible issue] Remove duplicate command mapping to prevent potential conflicts
✅ Remove duplicate command mapping to prevent potential conflicts
Remove the duplicate SET_DELAY_ENABLED command mapping which could cause unexpected behavior.
javascript/node/selenium-webdriver/lib/http.js [324-329]
[cmd.Name.SET_DELAY_ENABLED, post(`/session/:sessionId/fedcm/setdelayenabled`)],
[cmd.Name.CANCEL_DIALOG, post(`/session/:sessionId/fedcm/canceldialog`)],
[cmd.Name.SELECT_ACCOUNT, post(`/session/:sessionId/fedcm/selectaccount`)],
[cmd.Name.GET_FEDCM_TITLE, get(`/session/:sessionId/fedcm/gettitle`)],
[cmd.Name.GET_FEDCM_DIALOG_TYPE, get('/session/:sessionId/fedcm/getdialogtype')],
-[cmd.Name.SET_DELAY_ENABLED, post(`/session/:sessionId/fedcm/setdelayenabled`)],
Suggestion importance[1-10]: 7
Why: The suggestion removes a duplicate command mapping that could cause inconsistent behavior in the command execution system.
PR 14998 (2025-01-01) |
[possible issue] Add parameter validation to prevent null reference exceptions
✅ Add parameter validation to prevent null reference exceptions
Add null check for value parameter in FromJson method to prevent potential NullReferenceException when deserializing JSON.
dotnet/src/webdriver/Response.cs [74-76]
public static Response FromJson(string value)
{
+ if (string.IsNullOrEmpty(value))
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
Dictionary<string, object> rawResponse = JsonSerializer.Deserialize<Dictionary<string, object>>(value, s_jsonSerializerOptions)
- Apply this suggestion Suggestion importance[1-10]: 7
Why: Adding null validation for the input parameter is important for robustness and would prevent potential runtime errors. The current code assumes valid input which could lead to unclear error messages if null is passed.
PR 14946 (2024-12-26) |
[possible issue] Use locale-independent number formatting to handle port numbers consistently across all system languages
✅ Use locale-independent number formatting to handle port numbers consistently across all system languages
Instead of checking only for non-English locale, implement proper number formatting using a Locale-independent approach. Use String.valueOf() or Integer.toString() for port number conversion to avoid locale-specific formatting issues.
java/src/org/openqa/selenium/chrome/ChromeDriverService.java [287-291]
-args.add(String.format("--port=%d", getPort()));
-if(!Locale.getDefault(Locale.Category.FORMAT).getLanguage().equals("en")) {
- throw new NumberFormatException("Couldn't format the port numbers because the System Language is arabic: \"" + String.format("--port=%d", getPort()) +
- "\", please make sure to add the required arguments \"-Duser.language=en -Duser.region=US\" to your JVM, for more info please visit :" + "\n https://www.selenium.dev/documentation/webdriver/browsers/");
-}
+args.add("--port=" + String.valueOf(getPort()));
- Apply this suggestion Suggestion importance[1-10]: 9
Why: The suggestion addresses a critical issue by proposing a more robust solution using locale-independent number formatting, which would prevent formatting issues across all locales without requiring system language changes.
[possible issue] Ensure consistent locale-independent number formatting across all port number handling
✅ Ensure consistent locale-independent number formatting across all port number handling
The websocket port formatting is inconsistent with the main port handling and could face the same locale issues. Apply the same locale-independent formatting to the websocket port.
java/src/org/openqa/selenium/firefox/GeckoDriverService.java [223-230]
-args.add(String.format("--port=%d", getPort()));
-if(!Locale.getDefault(Locale.Category.FORMAT).getLanguage().equals("en")) {
- throw new NumberFormatException("Couldn't format the port numbers because the System Language is arabic: \"" + String.format("--port=%d", getPort()) +
- "\", please make sure to add the required arguments \"-Duser.language=en -Duser.region=US\" to your JVM, for more info please visit :" + "\n https://www.selenium.dev/documentation/webdriver/browsers/");
-}
+args.add("--port=" + String.valueOf(getPort()));
+int wsPort = PortProber.findFreePort();
+args.add("--websocket-port=" + String.valueOf(wsPort));
-int wsPort = PortProber.findFreePort();
-args.add(String.format("--websocket-port=%d", wsPort));
-
- Apply this suggestion Suggestion importance[1-10]: 8
Why: The suggestion identifies an important consistency issue where websocket port formatting could face the same locale-related problems as the main port, making the fix more comprehensive.
[general] Provide accurate error messages that reflect the actual system locale instead of assuming Arabic
✅ Provide accurate error messages that reflect the actual system locale instead of assuming Arabic
The error message incorrectly assumes the system language is Arabic when it's any non-English locale. Update the message to be more accurate and include the actual locale in the error message.
java/src/org/openqa/selenium/chrome/ChromeDriverService.java [289]
-throw new NumberFormatException("Couldn't format the port numbers because the System Language is arabic: \"" + String.format("--port=%d", getPort()) +
+throw new NumberFormatException("Couldn't format the port numbers due to non-English system locale '" + Locale.getDefault(Locale.Category.FORMAT) + "': \"" + String.format("--port=%d", getPort()) +
- Apply this suggestion Suggestion importance[1-10]: 7
Why: The suggestion improves error message accuracy by including the actual system locale rather than assuming Arabic, making debugging easier and preventing confusion for users with non-Arabic locales.
PR 14900 (2024-12-14) |
[possible issue] Add error handling for malformed event data to prevent null pointer exceptions
✅ Add error handling for malformed event data to prevent null pointer exceptions
The fetch_id method should handle cases where the event hash structure is invalid or missing expected keys to prevent NoMethodError.
rb/lib/selenium/webdriver/common/network.rb [76-77]
def fetch_id(event)
- event['request']['request']
+ event.dig('request', 'request') or raise ArgumentError, 'Invalid event structure: missing request ID'
end
- Apply this suggestion Suggestion importance[1-10]: 7
Why: Using dig and adding proper error handling for malformed event data is a significant improvement that prevents potential null pointer exceptions and provides clearer error messages.
PR 14898 (2024-12-13) |
[Possible issue] Properly handle file lock acquisition errors instead of silently ignoring them
✅ Properly handle file lock acquisition errors instead of silently ignoring them
Handle error cases in Lock::acquire() instead of using unwrap_or_default() which silently ignores lock failures. File locking is critical for preventing race conditions.
-file.lock_exclusive().unwrap_or_default();
+file.lock_exclusive().map_err(|e| anyhow!("Failed to acquire file lock: {}", e))?;
- Apply this suggestion Suggestion importance[1-10]: 9
Why: Critical security improvement that prevents silent failures in file locking mechanism. Proper error handling is essential for maintaining data integrity and preventing race conditions.
PR 14874 (2024-12-08) |
[General] Maintain consistent null parameter validation by throwing exceptions instead of silently handling null values
✅ Maintain consistent null parameter validation by throwing exceptions instead of silently handling null values
The DeleteCookieNamed method should throw an ArgumentNullException when name is null, similar to how AddCookie handles null parameters. This maintains consistency in null parameter handling across the class.
dotnet/src/webdriver/CookieJar.cs [99-107]
public void DeleteCookieNamed(string? name)
{
- if (name is not null)
+ if (name is null)
{
- Dictionary<string, object> parameters = new Dictionary<string, object>();
- parameters.Add("name", name);
- this.driver.InternalExecute(DriverCommand.DeleteCookie, parameters);
+ throw new ArgumentNullException(nameof(name));
}
+ Dictionary<string, object> parameters = new Dictionary<string, object>();
+ parameters.Add("name", name);
+ this.driver.InternalExecute(DriverCommand.DeleteCookie, parameters);
}
- Apply this suggestion Suggestion importance[1-10]: 8
Why: The suggestion improves code consistency and robustness by enforcing strict null parameter validation, aligning with the pattern used in other methods like AddCookie. This prevents potential issues from silent null handling.
PR 14819 (2024-11-27) |
[General] Simplify null check using null-coalescing operator for better readability and maintainability
✅ Simplify null check using null-coalescing operator for better readability and maintainability
The null-coalescing operator (??) should be used instead of the pattern matching expression to check for null StreamWriter, as it's more idiomatic in C# and clearer in intent.
dotnet/src/webdriver/Internal/Logging/FileLogHandler.cs [83-91]
-if (_streamWriter is not { } writer)
-{
- throw new ObjectDisposedException(nameof(FileLogHandler));
-}
+var writer = _streamWriter ?? throw new ObjectDisposedException(nameof(FileLogHandler));
lock (_lockObj)
{
writer.WriteLine($"{logEvent.Timestamp:yyyy-MM-dd HH:mm:ss.fff} {_levels[(int)logEvent.Level]} {logEvent.IssuedBy.Name}: {logEvent.Message}");
}
- Apply this suggestion Suggestion importance[1-10]: 5
Why: The suggestion improves code readability by using a more concise and idiomatic C# pattern. While valid, the impact is moderate as it's primarily a stylistic change.
PR 14804 (2024-11-25) |
[possible issue] Add null check for required parameter to prevent runtime errors
✅ Add null check for required parameter to prevent runtime errors
Add null check for target parameter in ConvertElement() since it's marked as nullable but the method assumes it's non-null.
dotnet/src/webdriver/Interactions/PointerInputDevice.cs [584-588]
private Dictionary<string, object> ConvertElement()
{
+ if (this.target == null)
+ {
+ throw new ArgumentNullException(nameof(target));
+ }
if (this.target is IWebDriverObjectReference element)
{
return element.ToDictionary();
}
- Apply this suggestion Suggestion importance[1-10]: 7
Why: The ConvertElement method assumes target is non-null but it's marked as nullable. Adding an explicit null check improves error handling and prevents runtime exceptions.
PR 14791 (2024-11-22) |
[possible issue] Remove duplicate version specification to prevent version ambiguity
✅ Remove duplicate version specification to prevent version ambiguity
Remove the duplicate '3.1.6' line from the .ruby-version file as it creates ambiguity about which version should be used.
+3.2.2
- 3.1.6
- Apply this suggestion Suggestion importance[1-10]: 9
Why: Having two different Ruby versions (3.2.2 and 3.1.6) in the .ruby-version file is a critical issue that could cause version conflicts and inconsistent behavior across different environments. The duplicate line should be removed to maintain a single, clear version specification.
PR 14759 (2024-11-15) |
[Best practice] Fix inconsistent code indentation to improve readability
✅ Fix inconsistent code indentation to improve readability
The indentation of the logger check block is inconsistent. Align the opening brace with the if statement.
dotnet/src/webdriver/Remote/RemoteWebDriver.cs [432-435]
if (_logger.IsEnabled(LogEventLevel.Warn))
- {
- _logger.Warn("CDP support for Firefox is deprecated and will be removed in future versions. Please switch to WebDriver BiDi.");
- }
+{
+ _logger.Warn("CDP support for Firefox is deprecated and will be removed in future versions. Please switch to WebDriver BiDi.");
+}
Suggestion importance[1-10]: 4
Why: The suggestion correctly identifies an indentation inconsistency in the code that affects readability, though it's a relatively minor issue that doesn't affect functionality.
PR 14742 (2024-11-11) |
[Possible bug] Add parameter validation to prevent null reference exceptions
✅ Add parameter validation to prevent null reference exceptions
Add null check for key parameter in SetPreferenceValue method to prevent potential issues with null keys.
dotnet/src/webdriver/Firefox/Preferences.cs [166-168]
private void SetPreferenceValue(string key, JsonNode? value)
{
+ if (key == null)
+ throw new ArgumentNullException(nameof(key));
if (!this.IsSettablePreference(key))
- Apply this suggestion Suggestion importance[1-10]: 7
Why: Adding null validation for method parameters is a crucial defensive programming practice that prevents potential null reference exceptions and improves code reliability.
PR 14737 (2024-11-10) |
[Best practice] Replace debug assertion with exception throw to properly handle unexpected states in production code
✅ Replace debug assertion with exception throw to properly handle unexpected states in production code
The Debug.Fail call with "Unreachable" suggests this code path should never be hit, but the code after it is still executed. Consider throwing an InvalidOperationException instead to fail fast if this "impossible" state is reached.
dotnet/src/webdriver/RelativeBy.cs [133-134]
-Debug.Fail("Unreachable");
-return elementsObj.Select(element => (IWebElement)element).ToList().AsReadOnly();
+throw new InvalidOperationException("Unexpected state: ReadOnlyCollection with non-zero elements");
- Apply this suggestion Suggestion importance[1-10]: 8
Why: This is a significant improvement for production code reliability. Replacing Debug.Fail with an exception throw ensures proper error handling in all environments and prevents silent failures in production.
PR 14736 (2024-11-09) |
[Maintainability] Enable or remove commented test attribute to maintain clean test code
✅ Enable or remove commented test attribute to maintain clean test code
Remove commented-out test attribute to either enable the test or remove unused code
dotnet/test/ie/IeSpecificTests.cs [363-364]
-//[Test]
+[Test]
public void InternetExplorerOptionsToString()
- Apply this suggestion Suggestion importance[1-10]: 7
Why: Commented-out test attributes can lead to confusion and maintenance issues. The test should either be properly enabled or removed to maintain code clarity.
PR 14723 (2024-11-07) |
[Enhancement] Correct the test function name to accurately reflect the browser being tested
✅ Correct the test function name to accurately reflect the browser being tested
Rename the test function to reflect that it's testing Edge browser instances, not Chrome instances.
py/test/selenium/webdriver/edge/edge_launcher_tests.py [28]
-def test_we_can_launch_multiple_chrome_instances(clean_driver, clean_service):
+def test_we_can_launch_multiple_edge_instances(clean_driver, clean_service):
- Apply this suggestion Suggestion importance[1-10]: 8
Why: The function name incorrectly refers to Chrome instances instead of Edge instances. This change improves code clarity and accuracy, preventing potential confusion for developers.
[Enhancement] Update the test function name to correctly identify the driver being tested
✅ Update the test function name to correctly identify the driver being tested
Replace 'chromedriver' with 'msedgedriver' in the test function name to accurately reflect the driver being tested.
py/test/selenium/webdriver/edge/edge_service_tests.py [29]
-def test_uses_chromedriver_logging(clean_driver, driver_executable) -> None:
+def test_uses_msedgedriver_logging(clean_driver, driver_executable) -> None:
- Apply this suggestion Suggestion importance[1-10]: 8
Why: The function name incorrectly refers to ChromeDriver instead of EdgeDriver. This change enhances code accuracy and readability, aligning the test name with its actual purpose.
[Enhancement] Correct the class name to accurately represent the service being tested
✅ Correct the class name to accurately represent the service being tested
Rename the class to reflect that it's testing EdgeDriverService, not ChromeDriverService.
py/test/selenium/webdriver/edge/edge_service_tests.py [106]
-class TestChromeDriverService:
+class TestEdgeDriverService:
- Apply this suggestion Suggestion importance[1-10]: 8
Why: The class name incorrectly refers to ChromeDriverService instead of EdgeDriverService. This change improves code consistency and prevents potential misunderstandings about the tested service.
This wiki is not where you want to be! Visit the Wiki Home for more useful links
Getting Involved
Triaging Issues
Releasing Selenium
Ruby Development
Python Bindings
Ruby Bindings
WebDriverJs
This content is being evaluated for where it belongs
Architectural Overview
Automation Atoms
HtmlUnitDriver
Lift Style API
LoadableComponent
Logging
PageFactory
RemoteWebDriver
Xpath In WebDriver
Moved to Official Documentation
Bot Style Tests
Buck
Continuous Integration
Crazy Fun Build
Design Patterns
Desired Capabilities
Developer Tips
Domain Driven Design
Firefox Driver
Firefox Driver Internals
Focus Stealing On Linux
Frequently Asked Questions
Google Summer Of Code
Grid Platforms
History
Internet Explorer Driver
InternetExplorerDriver Internals
Next Steps
PageObjects
RemoteWebDriverServer
Roadmap
Scaling WebDriver
SeIDE Release Notes
Selenium Emulation
Selenium Grid 4
Selenium Help
Shipping Selenium 3
The Team
TLC Meetings
Untrusted SSL Certificates
WebDriver For Mobile Browsers
Writing New Drivers