Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[java][BiDi] implement emulation.setNetworkConditions#16794

Merged
asolntsev merged 2 commits intoSeleniumHQ:trunkfrom
Delta456:emul_networkcond
Dec 24, 2025
Merged

[java][BiDi] implement emulation.setNetworkConditions#16794
asolntsev merged 2 commits intoSeleniumHQ:trunkfrom
Delta456:emul_networkcond

Conversation

@Delta456
Copy link
Member

@Delta456 Delta456 commented Dec 24, 2025

User description

🔗 Related Issues

💥 What does this PR do?

Implements emulation.setNetworkConditions from W3C spec https://w3c.github.io/webdriver-bidi/#command-emulation-setNetworkConditions

🔧 Implementation Notes

💡 Additional Considerations

🔄 Types of changes

  • New feature (non-breaking change which adds functionality and tests!)

PR Type

Enhancement


Description

  • Implements emulation.setNetworkConditions BiDi command from W3C spec

  • Adds SetNetworkConditionsParameters class for offline/online network emulation

  • Supports context and user context targeting for network conditions

  • Includes comprehensive tests for offline mode with contexts and user contexts


Diagram Walkthrough

flowchart LR
  A["Emulation API"] -->|"setNetworkConditions method"| B["SetNetworkConditionsParameters"]
  B -->|"offline/online config"| C["BiDi Command"]
  C -->|"contexts or userContexts"| D["Network Emulation"]
  E["Test Suite"] -->|"validates offline mode"| D
Loading

File Walkthrough

Relevant files
Enhancement
Emulation.java
Add setNetworkConditions method to Emulation                         

java/src/org/openqa/selenium/bidi/emulation/Emulation.java

  • Added setNetworkConditions() method to Emulation class
  • Method accepts SetNetworkConditionsParameters and sends BiDi command
  • Follows existing pattern with parameter validation
+6/-0     
SetNetworkConditionsParameters.java
Create SetNetworkConditionsParameters configuration class

java/src/org/openqa/selenium/bidi/emulation/SetNetworkConditionsParameters.java

  • New parameter class extending AbstractOverrideParameters
  • Constructor accepts Boolean for offline/online state
  • Supports contexts() and userContexts() for targeted emulation
  • Maps offline state to W3C spec format with networkConditions
+43/-0   
Tests
SetNetworkConditionsTest.java
Add comprehensive tests for network conditions emulation 

java/test/org/openqa/selenium/bidi/emulation/SetNetworkConditionsTest.java

  • Test for setting offline mode with specific browsing context
  • Test for setting offline mode with user context
  • Validates navigator.onLine property changes via script evaluation
  • Includes proper cleanup and reset of network conditions
+119/-0 

@selenium-ci selenium-ci added C-java Java Bindings B-devtools Includes everything BiDi or Chrome DevTools related labels Dec 24, 2025
@qodo-code-review
Copy link
Contributor

qodo-code-review bot commented Dec 24, 2025

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🟡
🎫 #1234
🔴 Ensure Selenium 2.48 triggers JavaScript in a link href when click() is invoked
(regression vs 2.47.1).
Verify/fix behavior specifically for Firefox 42.0 where the provided test case alerts on
click.
🟡
🎫 #5678
🔴 Prevent/resolve ConnectFailure (Connection refused) errors when instantiating multiple
ChromeDriver instances on Ubuntu 16.04 with Chrome 65 and ChromeDriver 2.35.
Ensure repeated ChromeDriver instantiation does not emit console connection-refused errors
after the first instance.
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

🔴
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Unsafe result casting: The helper isOnline assumes the script evaluation always returns EvaluateResultSuccess
with a present boolean value and can throw (ClassCastException/NoSuchElementException)
without providing actionable context if the evaluation fails or returns an unexpected
payload.

Referred Code
private Boolean isOnline(String contextId, Script script) {
  EvaluateResult result =
      script.evaluateFunctionInBrowsingContext(
          contextId, "navigator.onLine", false, Optional.empty());
  return (Boolean) ((EvaluateResultSuccess) result).getResult().getValue().get();
}

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Nullability ambiguity: The constructor accepts a nullable Boolean and treats null the same as false by clearing
networkConditions, which may be intended but should be confirmed against the BiDi spec and
callers’ expectations to avoid unintentionally disabling emulation due to a
missing/unspecified value.

Referred Code
public SetNetworkConditionsParameters(Boolean offline) {
  if (Boolean.TRUE.equals(offline)) {
    map.put("networkConditions", Map.of("type", "offline"));
  } else {
    map.put("networkConditions", null);
  }
}

Learn more about managing compliance generic rules or creating your own custom rules

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@Delta456 Delta456 changed the title [java][BiDi] implement emulation.setNetworkConditions [java][BiDi] implement emulation.setNetworkConditions Dec 24, 2025
@qodo-code-review
Copy link
Contributor

qodo-code-review bot commented Dec 24, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Add assertion to verify reset

In the canSetNetworkConditionsOfflineWithUserContext test, add an assertion to
verify that navigator.onLine is true after resetting the network conditions.

java/test/org/openqa/selenium/bidi/emulation/SetNetworkConditionsTest.java [102-106]

 // Reset
 emulation.setNetworkConditions(
     new SetNetworkConditionsParameters(false).userContexts(List.of(userContext)));
+assertThat(isOnline(contextId, script)).isTrue();
 
 context.close();
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: This suggestion correctly identifies a missing assertion in the test canSetNetworkConditionsOfflineWithUserContext, improving test completeness and ensuring the reset functionality is properly verified.

Medium
Support advanced network emulation parameters

Expand SetNetworkConditionsParameters to support advanced network emulation
parameters like latency and throughput, in addition to the offline state.

java/src/org/openqa/selenium/bidi/emulation/SetNetworkConditionsParameters.java [22-43]

+import java.util.HashMap;
+import java.util.Map;
+import org.openqa.selenium.internal.Require;
+
 public class SetNetworkConditionsParameters extends AbstractOverrideParameters {
 
   public SetNetworkConditionsParameters(Boolean offline) {
     if (Boolean.TRUE.equals(offline)) {
       map.put("networkConditions", Map.of("type", "offline"));
     } else {
       map.put("networkConditions", null);
     }
+  }
+
+  public SetNetworkConditionsParameters(long latency, long downloadThroughput, long uploadThroughput) {
+    Require.nonNegative("Latency", latency);
+    Require.nonNegative("Download throughput", downloadThroughput);
+    Require.nonNegative("Upload throughput", uploadThroughput);
+
+    Map<String, Object> networkConditions = new HashMap<>();
+    networkConditions.put("type", "network");
+    networkConditions.put("latency", latency);
+    networkConditions.put("downloadThroughput", downloadThroughput);
+    networkConditions.put("uploadThroughput", uploadThroughput);
+
+    map.put("networkConditions", networkConditions);
   }
 
   @Override
   public SetNetworkConditionsParameters contexts(java.util.List<String> contexts) {
     super.contexts(contexts);
     return this;
   }
 
   @Override
   public SetNetworkConditionsParameters userContexts(java.util.List<String> userContexts) {
     super.userContexts(userContexts);
     return this;
   }
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: This is a valid feature enhancement suggestion that would make the setNetworkConditions implementation more complete by supporting parameters like latency and throughput, but it is not a bug in the current PR's scope.

Low
Learned
best practice
Use finally for resource cleanup

Replace the nested try/catch close logic with a single try/finally that always
calls context.close() to ensure deterministic cleanup and avoid swallowing close
failures.

java/test/org/openqa/selenium/bidi/emulation/SetNetworkConditionsTest.java [81-117]

 try {
   BrowsingContext context =
       new BrowsingContext(
           driver, new CreateContextParameters(WindowType.TAB).userContext(userContext));
   String contextId = context.getId();
 
   try {
     driver.switchTo().window(contextId);
 
     Emulation emulation = new Emulation(driver);
     Script script = new Script(driver);
 
     context.navigate(appServer.whereIs("formPage.html"), ReadinessState.COMPLETE);
 
     assertThat(isOnline(contextId, script)).isTrue();
 
     // Set offline
     emulation.setNetworkConditions(
         new SetNetworkConditionsParameters(true).userContexts(List.of(userContext)));
     assertThat(isOnline(contextId, script)).isFalse();
 
     // Reset
     emulation.setNetworkConditions(
         new SetNetworkConditionsParameters(false).userContexts(List.of(userContext)));
-
+  } finally {
     context.close();
-  } catch (Exception e) {
-    try {
-      context.close();
-    } catch (Exception closeException) {
-      // Ignore
-    }
-    throw e;
   }
 } finally {
   browser.removeUserContext(userContext);
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why:
Relevant best practice - Always wrap creation of external contexts/resources in try/finally and perform explicit cleanup in finally to prevent leaks even when assertions or exceptions occur.

Low
  • Update

@asolntsev asolntsev merged commit d020dff into SeleniumHQ:trunk Dec 24, 2025
74 of 75 checks passed
@Delta456 Delta456 deleted the emul_networkcond branch December 24, 2025 21:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

B-devtools Includes everything BiDi or Chrome DevTools related C-java Java Bindings Review effort 3/5

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants