Skip to content

Add Python BiDi examples for Register Basic Auth (network.authRequired) - #2741

Merged
diemol merged 4 commits into
trunkfrom
feature/bidi-python-basic-auth-examples
Jul 23, 2026
Merged

Add Python BiDi examples for Register Basic Auth (network.authRequired)#2741
diemol merged 4 commits into
trunkfrom
feature/bidi-python-basic-auth-examples

Conversation

@diemol

@diemol diemol commented Jul 23, 2026

Copy link
Copy Markdown
Member

Thanks for contributing to the Selenium site and documentation!
A PR well described will help maintainers to review and merge it quickly

Before submitting your PR, please check our contributing guidelines.
Avoid large PRs, and help reviewers by making them as simple and short as possible.

Description

Adds Python examples for the BiDi network.authRequired phase to examples/python/tests/bidi/test_network_commands.py, and wires up the four remaining Python {{< badge-code >}} placeholders on the Network Commands/Events doc (en, ja, pt-br, zh-cn):

  • Continue request blocked at authRequired phase with credentials (test_continue_with_auth_credentials)
  • ...without credentials (test_continue_without_auth_credentials)
  • Cancel request blocked at authRequired phase (test_cancel_auth)
  • Auth Required event (test_auth_required_event)

Motivation and Context

Reported in #815 ("Please add sample python code for BiDi APIs Register Basic Auth and Network Interception"). Some other Network sections have gained Python examples since 2021, but the "Register Basic Auth" scenarios specifically were still {{< badge-code >}} placeholders.

selenium already has purpose-built Python APIs for this — driver.network.add_auth_handler(username, password) and the more flexible driver.network.add_authentication_handler(callback) (with AuthenticationRequest.provide_credentials()/.cancel()) — they just had no doc example or test coverage.

Why a new firefox_bidi driver type

The "without credentials" and "cancel" scenarios fall back to (or trigger failure of) the browser's native basic-auth prompt. Chrome does not expose that native dialog as a WebDriver Alert, so a test that waits for/dismisses it deadlocks — I hit this directly (driver.get() hung indefinitely on Chrome). The Java and JavaScript examples for these same scenarios already work around this by using Firefox specifically. I added a matching firefox_bidi option to the driver_type fixture in conftest.py and used it only for these four new tests; the existing Chrome-based bidi tests are untouched.

All 8 tests in the file (4 existing + 4 new) pass consistently against real Chrome/Firefox browsers, run 3x with no flakiness.

Types of changes

  • Change to the site (I have double-checked the Netlify deployment, and my changes look good)
  • Code example added (and I also added the example to all translated languages)
  • Improved translation
  • Added new translation (and I also added a notice to each document missing translation)

Checklist

  • I have read the contributing document.
  • I have used hugo to render the site/docs locally and I am sure it works.

Closes #815.

Fills the last Python gaps on the Network Commands/Events doc for the
authRequired phase: continuing with credentials, continuing without
credentials, cancelling, and the Auth Required event.

driver.network.add_auth_handler()/add_authentication_handler() are
Chrome-only-hanging when the browser falls back to its native prompt:
Chrome does not expose that dialog as a WebDriver Alert, so a test that
needs to dismiss or observe it deadlocks. Java and JavaScript already
work around this by running these specific scenarios against Firefox;
this adds a matching "firefox_bidi" driver_type to conftest.py and uses
it only for the four new tests, leaving the existing Chrome-based bidi
tests untouched.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Add Python BiDi Basic Auth (network.authRequired) examples + Firefox BiDi test driver

✨ Enhancement 🧪 Tests 📝 Documentation 🕐 20-40 Minutes

Grey Divider

AI Description

• Add Python BiDi examples for network.authRequired credentials, fallback, cancel, and event
 handling.
• Introduce a firefox_bidi pytest driver type to avoid Chrome basic-auth dialog hangs.
• Wire Python codeblocks into Network docs (en/ja/pt-br/zh-cn) with Selenium 4.46 badges.
Diagram

graph TD
A["Network docs (*.md)"] --> B["Python gh-codeblock refs"] --> C["test_network_commands.py"] --> D["conftest.py driver fixture"]
D --> E["Chrome BiDi driver"]
D --> F["Firefox BiDi driver"] --> G{{"Basic Auth endpoint"}}
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Skip/xfail auth-challenge tests on Chrome instead of adding firefox_bidi
  • ➕ Avoids expanding the driver fixture API surface
  • ➕ Keeps all BiDi tests under a single driver_type value
  • ➖ Docs/examples still need a reliable runnable backing test; skipping reduces coverage
  • ➖ Still requires contributors/CI to understand why Chrome hangs without a positive example path
2. Use a local basic-auth test server with deterministic prompt behavior
  • ➕ Removes dependency on external site availability/content
  • ➕ Could tailor challenges/realms/status codes precisely
  • ➖ Adds infra complexity (server lifecycle, ports, TLS) to examples/tests
  • ➖ Does not solve Chrome’s native dialog non-exposure; still needs a browser strategy
3. Rely only on provide_credentials() path (no fallback/cancel examples)
  • ➕ Simpler and more likely to be cross-browser
  • ➕ Avoids native dialog interactions altogether
  • ➖ Leaves the original documentation gap for fallback/cancel semantics
  • ➖ Reduces practical guidance for real-world authRequired handling

Recommendation: Keep the PR’s approach: a dedicated firefox_bidi driver type for the auth-challenge scenarios is a pragmatic, low-impact workaround that matches existing Java/JS guidance and preserves executable coverage for all four authRequired examples. Consider (optionally, later) consolidating driver selection behind a helper or adding a short doc note that these particular Python snippets are validated on Firefox due to Chrome dialog limitations.

Files changed (6) +113 / -16

Tests (1) +73 / -0
test_network_commands.pyAdd BiDi authRequired Basic Auth scenario tests (Firefox-only) +73/-0

Add BiDi authRequired Basic Auth scenario tests (Firefox-only)

• Adds four new tests covering authRequired continuation with credentials, fallback without credentials, cancellation, and the authRequired event payload. Uses Firefox-only execution to avoid Chrome hanging on the native basic-auth dialog, and adds minimal DOM assertions using 'By' plus explicit waits for the alert case.

examples/python/tests/bidi/test_network_commands.py

Documentation (4) +32 / -16
network.en.mdReplace Python placeholders with authRequired codeblocks (EN) +8/-4

Replace Python placeholders with authRequired codeblocks (EN)

• Replaces four remaining Python 'badge-code' placeholders in the Network docs with 'badge-version 4.46' and 'gh-codeblock' includes pointing at the new Python tests for authRequired flows and event handling.

website_and_docs/content/documentation/webdriver/bidi/w3c/network.en.md

network.ja.mdReplace Python placeholders with authRequired codeblocks (JA) +8/-4

Replace Python placeholders with authRequired codeblocks (JA)

• Mirrors the EN doc updates by adding Selenium 4.46 Python codeblocks for the authRequired credential/fallback/cancel flows and the Auth Required event section.

website_and_docs/content/documentation/webdriver/bidi/w3c/network.ja.md

network.pt-br.mdReplace Python placeholders with authRequired codeblocks (PT-BR) +8/-4

Replace Python placeholders with authRequired codeblocks (PT-BR)

• Mirrors the EN doc updates by adding Selenium 4.46 Python codeblocks for the remaining authRequired-related command/event sections.

website_and_docs/content/documentation/webdriver/bidi/w3c/network.pt-br.md

network.zh-cn.mdReplace Python placeholders with authRequired codeblocks (ZH-CN) +8/-4

Replace Python placeholders with authRequired codeblocks (ZH-CN)

• Mirrors the EN doc updates by adding Selenium 4.46 Python codeblocks for authRequired continuation, fallback, cancellation, and event handling.

website_and_docs/content/documentation/webdriver/bidi/w3c/network.zh-cn.md

Other (1) +8 / -0
conftest.pyIntroduce firefox_bidi driver_type fixture option +8/-0

Introduce firefox_bidi driver_type fixture option

• Extends the 'driver' fixture to support a 'firefox_bidi' marker that enables BiDi on Firefox. Includes inline rationale explaining Chrome’s native basic-auth prompt limitations for these tests.

examples/python/tests/conftest.py

@netlify

netlify Bot commented Jul 23, 2026

Copy link
Copy Markdown

Deploy Preview for selenium-dev ready!

Name Link
🔨 Latest commit 8686a42
🔍 Latest deploy log https://app.netlify.com/projects/selenium-dev/deploys/6a6210b4ef105000080a93ed
😎 Deploy Preview https://deploy-preview-2741--selenium-dev.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

Update gh-codeblock line references across en/ja/pt-br/zh-cn to match.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@qodo-code-review

qodo-code-review Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (1) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 10 rules

Grey Divider


Remediation recommended

1. admin credentials hard-coded 📘 Rule violation ⛨ Security
Description
The new BiDi auth examples hard-code Basic Auth credentials (admin/admin) in committed test
code. This violates the rule against committing credentials and makes it easy to accidentally
propagate real secrets in future edits.
Code

examples/python/tests/bidi/test_network_commands.py[82]

+    callback_id = driver.network.add_auth_handler("admin", "admin")
Evidence
PR Compliance ID 2141351 disallows committing hard-coded credentials. The added auth handler and
provide_credentials() calls include literal username/password strings (admin, admin).

Rule 2141351: Disallow hard-coded secrets and credentials in committed code
examples/python/tests/bidi/test_network_commands.py[80-83]
examples/python/tests/bidi/test_network_commands.py[131-134]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Hard-coded credentials (`admin`/`admin`) were added to committed code.

## Issue Context
Compliance requires that credentials are not committed in source; tests/examples should load them from environment variables (and optionally skip when not provided).

## Fix Focus Areas
- examples/python/tests/bidi/test_network_commands.py[80-89]
- examples/python/tests/bidi/test_network_commands.py[131-134]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Env var not restored ✓ Resolved 🐞 Bug ☼ Reliability
Description
The driver fixture sets MOZ_ENABLE_WAYLAND="0" for firefox_bidi but never restores the prior
value, so later tests in the same pytest process can inherit a modified environment unexpectedly.
This makes test behavior order-dependent and can break scenarios that rely on the caller’s original
env var state (including the variable being previously unset).
Code

examples/python/tests/conftest.py[R37-44]

+    elif driver_type == "firefox_bidi":
+        # Chrome does not expose its native basic-auth dialog as a WebDriver
+        # Alert, so auth-challenge tests that need to observe/dismiss it use
+        # Firefox instead, matching the Java and JavaScript BiDi examples.
+        os.environ["MOZ_ENABLE_WAYLAND"] = "0"
+        options = webdriver.FirefoxOptions()
+        options.enable_bidi = True
+        driver = webdriver.Firefox(options=options)
Evidence
The fixture sets os.environ["MOZ_ENABLE_WAYLAND"] = "0" when driver_type == "firefox_bidi", then
yields and only calls driver.quit() during teardown; there is no code that restores/removes the
env var afterward.

examples/python/tests/conftest.py[25-51]
examples/python/tests/conftest.py[34-47]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The `driver` fixture mutates the process-global `os.environ["MOZ_ENABLE_WAYLAND"]` in the new `firefox_bidi` branch but does not restore it after yielding the driver, leaking state across tests.

### Issue Context
`os.environ` changes persist for the lifetime of the Python process; pytest runs many tests in the same process, so this can create order-dependent failures.

### Fix Focus Areas
- examples/python/tests/conftest.py[25-51]

### Implementation notes
- Before setting `MOZ_ENABLE_WAYLAND`, capture whether it was set and what its value was.
- After `yield` (in teardown), restore it:
 - If it was previously set: set it back to the saved value.
 - If it was previously unset: `os.environ.pop("MOZ_ENABLE_WAYLAND", None)`.
- Consider applying the same restoration to the existing `firefox` branch for consistency.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. gh-codeblock ranges now stale ✓ Resolved 📘 Rule violation ≡ Correctness
Description
This PR changes examples/python/tests/bidi/test_network_commands.py line numbers but does not
update all existing gh-codeblock line ranges that reference it, causing rendered docs snippets to
be truncated or incorrect. For example, one snippet ends at finally: and another omits the final
assertion line.
Code

examples/python/tests/bidi/test_network_commands.py[20]

+from selenium.webdriver.common.by import By
Evidence
PR Compliance ID 2141349 requires updating documentation gh-codeblock line ranges when referenced
examples/... files change. The docs reference #L40-L58 and #L61-L76, but in the updated Python
file those ranges end before critical lines (e.g., the body under finally: and the `assert not
requests`), demonstrating the ranges are no longer aligned with the intended snippet.

Rule 2141349: Update gh-codeblock line ranges when examples change
website_and_docs/content/documentation/webdriver/bidi/w3c/network.en.md[128-139]
examples/python/tests/bidi/test_network_commands.py[41-59]
website_and_docs/content/documentation/webdriver/bidi/w3c/network.en.md[154-165]
examples/python/tests/bidi/test_network_commands.py[62-77]
website_and_docs/content/documentation/webdriver/bidi/w3c/network.ja.md[138-174]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Changing `examples/python/tests/bidi/test_network_commands.py` shifted line numbers, but existing docs `gh-codeblock` references to this file were not all updated, so the documentation will render incorrect/truncated snippets.

## Issue Context
Multiple docs pages reference `test_network_commands.py` using GitHub `#Lx-Ly` ranges. After the example file changes, those ranges must be updated to keep the intended snippet boundaries.

## Fix Focus Areas
- examples/python/tests/bidi/test_network_commands.py[18-22]
- website_and_docs/content/documentation/webdriver/bidi/w3c/network.en.md[13-57]
- website_and_docs/content/documentation/webdriver/bidi/w3c/network.en.md[128-176]
- website_and_docs/content/documentation/webdriver/bidi/w3c/network.ja.md[138-175]
- website_and_docs/content/documentation/webdriver/bidi/w3c/network.pt-br.md[138-175]
- website_and_docs/content/documentation/webdriver/bidi/w3c/network.zh-cn.md[138-175]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Qodo Logo

Comment thread examples/python/tests/bidi/test_network_commands.py
Comment thread examples/python/tests/bidi/test_network_commands.py
Comment thread examples/python/tests/conftest.py
@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit b35de08

- Fix stale gh-codeblock line ranges for the four pre-existing Python
  sections (Add/Remove intercept, Fail request, Add/remove request
  handler): adding the By import shifted every line below it by 1,
  which the previous commits missed since they only tracked the new
  functions appended at the end of the file.
- Use pytest's monkeypatch.setenv instead of raw os.environ mutation
  for MOZ_ENABLE_WAYLAND, so it's restored after each test instead of
  leaking into later tests in the same process (applies to both the
  existing "firefox" and new "firefox_bidi" driver types).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@qodo-code-review

Copy link
Copy Markdown
Contributor

Code review by qodo was updated up to the latest commit 8686a42

@diemol
diemol merged commit aa606a8 into trunk Jul 23, 2026
10 checks passed
@diemol
diemol deleted the feature/bidi-python-basic-auth-examples branch July 23, 2026 13:26
selenium-ci added a commit that referenced this pull request Jul 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[🚀 Feature]: BiDi APIs Register Basic Auth

1 participant