Skip to content

Replace implicit lambda workaround with EC.alert_is_present in Python alert examples (Fixes #2548)#2589

Merged
diemol merged 6 commits into
SeleniumHQ:trunkfrom
beinghumantester:issue-2548-use-ec-alert-is-present
Jul 19, 2026
Merged

Replace implicit lambda workaround with EC.alert_is_present in Python alert examples (Fixes #2548)#2589
diemol merged 6 commits into
SeleniumHQ:trunkfrom
beinghumantester:issue-2548-use-ec-alert-is-present

Conversation

@beinghumantester

@beinghumantester beinghumantester commented Feb 22, 2026

Copy link
Copy Markdown
Contributor

User description

Description

Replaces the implicit lambda-based alert wait with the purpose-built
EC.alert_is_present() expected condition in all three Python alert examples.

The previous implementation used:

wait.until(lambda d: d.switch_to.alert)

This has been updated to:

alert = wait.until(EC.alert_is_present())

Motivation and Context

The examples previously used a lambda workaround to wait for alerts. While functional, Selenium provides a dedicated expected condition specifically designed for this use case.

Using EC.alert_is_present():

  • Improves readability and makes intent explicit
  • Aligns Python examples with official Selenium best practices
  • Makes the code clearer for users learning alert handling
  • Consistent with how other languages handle alert waiting in the docs

All three Python alert examples have been updated: Alert, Confirm, and Prompt.

Files Reviewed but Intentionally Not Changed

test_expected_conditions.py

Contains wait.until(lambda _ : revealed.is_displayed()) — left unchanged because no EC equivalent exists for an already-located element. EC.visibility_of_element_located() requires a locator tuple, not an existing WebElement.

test_waits.py

Contains two lambdas, both intentionally left unchanged:

  • lambda _ : revealed.is_displayed() — same reasoning as above
  • lambda _ : revealed.send_keys("Displayed") or True — custom condition that performs an action and returns True. No direct EC equivalent exists for this pattern.

Types of Changes

  • Change to the site (I have double-checked the Netlify deployment, and my changes look good)

Checklist

  • I have read the contributing document
  • I have used Hugo to render the site/docs locally and verified the changes
Screenshot 2026-02-22 151029

PR Type

Enhancement


Description

  • Replace lambda workaround with EC.alert_is_present() in Python alert examples

  • Add import for expected_conditions module

  • Improves code readability and aligns with Selenium best practices

  • Updates all three alert test cases (Alert, Confirm, Prompt)


Diagram Walkthrough

flowchart LR
  A["Lambda workaround<br/>wait.until(lambda d: d.switch_to.alert)"] -- "Replace with" --> B["EC.alert_is_present()<br/>wait.until(EC.alert_is_present())"]
  C["Import added<br/>expected_conditions as EC"] --> B
  B --> D["Three test cases updated<br/>Alert, Confirm, Prompt"]
Loading

File Walkthrough

Relevant files
Enhancement
test_alerts.py
Replace lambda alert waits with EC.alert_is_present()       

examples/python/tests/interactions/test_alerts.py

  • Added import for expected_conditions module from
    selenium.webdriver.support
  • Replaced lambda-based alert wait with EC.alert_is_present() in
    test_alert_popup()
  • Replaced lambda-based alert wait with EC.alert_is_present() in
    test_confirm_popup()
  • Replaced lambda-based alert wait with EC.alert_is_present() in
    test_prompt_popup()
+5/-4     

Replace implicit lambda workaround with purpose-built expected
condition for alert handling in all three Python alert examples.
Fixes SeleniumHQ#2548
@netlify

netlify Bot commented Feb 22, 2026

Copy link
Copy Markdown

Deploy Preview for selenium-dev ready!

Name Link
🔨 Latest commit bf8608e
🔍 Latest deploy log https://app.netlify.com/projects/selenium-dev/deploys/6a5bfb1dea0eda00088e8562
😎 Deploy Preview https://deploy-preview-2589--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.

@qodo-code-review

qodo-code-review Bot commented Feb 22, 2026

Copy link
Copy Markdown
Contributor

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
🎫 No ticket provided
  • Create ticket/issue
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: Robust Error Handling and Edge Case Management

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

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: Security-First Input Validation and Data Handling

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

Status: Passed

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

@qodo-code-review

qodo-code-review Bot commented Feb 22, 2026

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Always ensure driver quits

Wrap the browser lifecycle logic in a try...finally block to ensure
driver.quit() is always called, preventing orphaned browser processes if a test
fails.

examples/python/tests/interactions/test_alerts.py [11-22]

 driver = webdriver.Chrome()
-driver.get(url)
-...
-driver.quit()
+try:
+    driver.get(url)
+    ...
+finally:
+    driver.quit()

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: This is a crucial improvement for test stability, as it correctly identifies that a test failure would leave an orphaned browser process, and suggests a standard try...finally block to ensure proper resource cleanup.

Medium
  • Update

@VietND96
VietND96 requested a review from cgoldberg February 24, 2026 23:39

@cgoldberg cgoldberg left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this adds an import and shifts the line numbers, the codeblocks in the example page need to be adjusted to match.

The line numbers that need to be changed are in:

website_and_docs/content/documentation/webdriver/interactions/alerts.en.md (and alerts.ja.md, alerts.pt-br.md, alerts.zh-cn.md)

Other than that, I think this change is fine.

Comment thread examples/python/tests/interactions/test_alerts.py Outdated
@cgoldberg

Copy link
Copy Markdown
Member

@beinghumantester please make the suggested changes and update your branch if you want this merged.

@beinghumantester

Copy link
Copy Markdown
Contributor Author

@cgoldberg

I have updated the Python codeblock line references in alerts.en.md, alerts.ja.md, alerts.pt-br.md, and alerts.zh-cn.md so the rendered snippets match the modified example file.

Please take another look when you have time.

@qodo-code-review

qodo-code-review Bot commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 10 rules

Grey Divider


Informational

1. Whitespace-only blank line ✓ Resolved 🐞 Bug ⚙ Maintainability
Description
A whitespace-only blank line was added after the first alert assertion, creating unnecessary diff
noise and potentially tripping whitespace checks. This is at the end of test_alert_popup() right
before driver.quit().
Code

examples/python/tests/interactions/test_alerts.py[21]

+    
Evidence
The file contains a blank line consisting of spaces immediately after the assertion, visible in the
current PR branch file content.

examples/python/tests/interactions/test_alerts.py[18-22]

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

### Issue description
`examples/python/tests/interactions/test_alerts.py` contains a blank line with spaces after `assert text == "Sample alert"`. This should be an empty line with no trailing whitespace.

### Issue Context
Whitespace-only lines add noise to diffs and can fail whitespace gates (e.g., `git diff --check`) in some CI setups.

### Fix Focus Areas
- examples/python/tests/interactions/test_alerts.py[20-22]

ⓘ 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/interactions/test_alerts.py Outdated
Addresses cgoldberg's review comment about the trailing whitespace,
and corrects the gh-codeblock line ranges in alerts.en.md,
alerts.ja.md, alerts.pt-br.md, and alerts.zh-cn.md. The previous
update widened each range by one extra line on both ends instead of
shifting by the single line the new import adds, so the rendered
Python snippets pulled in driver.get(url) and the assert line that
the other language tabs intentionally omit.

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 c5b7ae5

@qodo-code-review

Copy link
Copy Markdown
Contributor

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

@diemol
diemol merged commit e6c5cb7 into SeleniumHQ:trunk Jul 19, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants