Skip to content

style: apply safe ruff lint fixes repo-wide#4755

Open
rnetser wants to merge 3 commits intoRedHatQE:mainfrom
rnetser:chore/safe-ruff-fixes
Open

style: apply safe ruff lint fixes repo-wide#4755
rnetser wants to merge 3 commits intoRedHatQE:mainfrom
rnetser:chore/safe-ruff-fixes

Conversation

@rnetser
Copy link
Copy Markdown
Collaborator

@rnetser rnetser commented May 6, 2026

What this PR does / why we need it:

Apply automated ruff lint fixes across 33 files. All fixes are behavior-preserving mechanical transformations:

  • SIM118: remove redundant .keys() in dict membership tests
  • SIM201: not x == yx != y
  • PLC0206: dict iteration with .items() instead of bracket access
  • PERF102: .items().values() where only value used
  • C403: set([...]){...}
  • C408: dict(...){...}
  • C414: sorted(list(...))sorted(...)
  • UP031: % format → f-string
  • B008: mutable default arg → module constant
  • LOG015: logging.error()LOGGER.error()

Part of the incremental lint cleanup series:

Assisted-by: Claude noreply@anthropic.com

Which issue(s) this PR fixes:
Special notes for reviewer:

All changes are automated ruff fixes. No manual edits. Each fix category is a well-known safe transformation.

jira-ticket:

Summary by CodeRabbit

Release Notes

  • Refactor
    • Improved code quality across test utilities and helper functions by simplifying dictionary operations and membership checks.
    • Streamlined conditional logic using more idiomatic Python patterns for enhanced readability.
    • Refined fixture implementations with cleaner iteration and comprehension syntax.
    • Updated assertion logic for consistency and maintainability.

Apply automated ruff lint fixes across 33 files:
- SIM118: remove redundant .keys() in dict membership tests
- SIM201: not x == y to x != y
- PLC0206: dict iteration with .items() instead of bracket access
- PERF102: .items() to .values() where only value used
- C403: set([...]) to {...}
- C408: dict(...) to {...}
- C414: sorted(list(...)) to sorted(...)
- UP031: % format to f-string
- B008: mutable default arg to module constant
- LOG015: logging.error() to LOGGER.error()

Assisted-by: Claude <noreply@anthropic.com>
Signed-off-by: rnetser <rnetser@redhat.com>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 6, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

This PR applies systematic code quality improvements across the test suite and utilities, primarily removing redundant .keys() calls in dictionary operations, simplifying boolean expressions, and modernizing string formatting patterns. All changes are localized, non-breaking refactors that improve readability without altering observable behavior.

Changes

Dictionary Membership & Code Style Refactoring

Layer / File(s) Summary
Dictionary Membership Cleanup
tests/conftest.py, tests/infrastructure/..., tests/install_upgrade_operators/..., tests/network/..., tests/storage/..., tests/utils.py, tests/virt/..., utilities/infra.py, utilities/network.py, utilities/virt.py
Removes in dict.keys() patterns, replacing with direct in dict membership tests; updates label/volume/capacity checks to iterate dict keys directly instead of explicit .keys() calls.
Dictionary Iteration & Unpacking
conftest.py, scripts/quarantine_stats/generate_dashboard.py, tests/install_upgrade_operators/json_patch/test_json_patch_annotation_multiple_updates.py, tests/scale/test_scale_benchmark.py, tests/virt/node/descheduler/conftest.py
Changes key-only iteration with index lookups to .items() unpacking; updates loop over dict.values() instead of keys; simplifies cleanup iteration by unpacking saved state directly.
Boolean Expression Simplification
tests/storage/cdi_upload/test_upload_virtctl.py, tests/storage/golden_image/test_cached_snapshots.py, tests/virt/node/gpu/vgpu/test_rhel_vm_with_vgpu.py
Replaces not x == y with x != y for clearer conditional logic in fixture guards and test assertions.
Format String & Comprehension Refactors
conftest.py, scripts/tests_analyzer/pytest_marker_analyzer.py, tests/infrastructure/golden_images/update_boot_source/test_ssp_data_sources.py, tests/infrastructure/instance_types/test_common_vm_preference.py, tests/install_upgrade_operators/csv/csv_permissions_audit/test_csv_permissions_audit.py, tests/network/kubemacpool/utils.py, tests/network/l2_bridge/libl2bridge.py, tests/network/sriov/libsriov.py, tests/virt/cluster/common_templates/general/test_base_template.py, tests/virt/node/high_performance_vm/test_numa.py, tests/virt/node/hyperv_support/test_hyperv_features_in_vm.py
Modernizes string formatting from percent-style to generator expressions; converts set([...]) to {...} comprehension syntax; updates dict construction from dict(key=value) to {key: value} literals; refactors error-handling and parameter-packing logic.
Logging & Configuration Extraction
tests/infrastructure/vm_console_proxy/utils.py, utilities/storage.py
Replaces direct logging.error() calls with configured LOGGER instance; extracts repeated shlex.split() computation from function default parameter into module-level _DEFAULT_DISK_SERIAL_COMMAND constant for initialization-time evaluation.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.81% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: applying automated ruff lint fixes repository-wide with safe, behavior-preserving transformations.
Description check ✅ Passed The description is comprehensive and well-structured. It explains what the PR does, lists all ten ruff fix categories applied, notes its place in the cleanup series, and credits the assistant. All key sections are addressed.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 6, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.67%. Comparing base (b4ad2e0) to head (86be6fe).
⚠️ Report is 139 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4755      +/-   ##
==========================================
+ Coverage   98.63%   98.67%   +0.03%     
==========================================
  Files          25       25              
  Lines        2420     2485      +65     
==========================================
+ Hits         2387     2452      +65     
  Misses         33       33              
Flag Coverage Δ
utilities 98.67% <ø> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@rnetser
Copy link
Copy Markdown
Collaborator Author

rnetser commented May 6, 2026

/build-and-push-container

@openshift-virtualization-qe-bot-4
Copy link
Copy Markdown

Report bugs in Issues

Welcome! 🎉

This pull request will be automatically processed with the following features:

🔄 Automatic Actions

  • Reviewer Assignment: Reviewers are automatically assigned based on the OWNERS file in the repository root
  • Size Labeling: PR size labels (XS, S, M, L, XL, XXL) are automatically applied based on changes
  • Issue Creation: A tracking issue is created for this PR and will be closed when the PR is merged or closed
  • Branch Labeling: Branch-specific labels are applied to track the target branch
  • Auto-verification: Auto-verified users have their PRs automatically marked as verified
  • Labels: Enabled categories: branch, can-be-merged, cherry-pick, has-conflicts, hold, needs-rebase, size, verified, wip

📋 Available Commands

PR Status Management

  • /wip - Mark PR as work in progress (adds WIP: prefix to title)
  • /wip cancel - Remove work in progress status
  • /hold - Block PR merging (approvers only)
  • /hold cancel - Unblock PR merging
  • /verified - Mark PR as verified
  • /verified cancel - Remove verification status
  • /reprocess - Trigger complete PR workflow reprocessing (useful if webhook failed or configuration changed)
  • /regenerate-welcome - Regenerate this welcome message

Review & Approval

  • /lgtm - Approve changes (looks good to me)
  • /approve - Approve PR (approvers only)
  • /assign-reviewers - Assign reviewers based on OWNERS file
  • /assign-reviewer @username - Assign specific reviewer
  • /check-can-merge - Check if PR meets merge requirements

Testing & Validation

  • /retest tox - Run Python test suite with tox
  • /retest build-container - Rebuild and test container image
  • /retest verify-bugs-are-open - verify-bugs-are-open
  • /retest all - Run all available tests

Container Operations

  • /build-and-push-container - Build and push container image (tagged with PR number)
    • Supports additional build arguments: /build-and-push-container --build-arg KEY=value

Cherry-pick Operations

  • /cherry-pick <branch> - Schedule cherry-pick to target branch when PR is merged
    • Multiple branches: /cherry-pick branch1 branch2 branch3

Label Management

  • /<label-name> - Add a label to the PR
  • /<label-name> cancel - Remove a label from the PR

✅ Merge Requirements

This PR will be automatically approved when the following conditions are met:

  1. Approval: /approve from at least one approver
  2. LGTM Count: Minimum 2 /lgtm from reviewers
  3. Status Checks: All required status checks must pass
  4. No Blockers: No wip, hold, has-conflicts labels and PR must be mergeable (no conflicts)
  5. Verified: PR must be marked as verified

📊 Review Process

Approvers and Reviewers

Approvers:

  • EdDev
  • dshchedr
  • jpeimer
  • myakove
  • rnetser
  • vsibirsk

Reviewers:

  • Ahmad-Hafe
  • Anatw
  • EdDev
  • OhadRevah
  • RoniKishner
  • SamAlber
  • acinko-rh
  • akri3i
  • albarker-rh
  • azhivovk
  • dalia-frank
  • dshchedr
  • ema-aka-young
  • frenzyfriday
  • geetikakay
  • guchen11
  • hmeir
  • josemacassan
  • jpeimer
  • kbidarkar
  • kgoldbla
  • kshvaika
  • mijankow
  • nirdothan
  • orelmisan
  • rlobillo
  • rnetser
  • sarahbx
  • servolkov
  • vsibirsk
  • yossisegev
Available Labels
  • hold
  • verified
  • wip
  • lgtm
  • approve
AI Features
  • Cherry-Pick Conflict Resolution: Enabled (claude/claude-opus-4-6[1m])

💡 Tips

  • WIP Status: Use /wip when your PR is not ready for review
  • Verification: The verified label is removed on new commits unless the push is detected as a clean rebase
  • Cherry-picking: Cherry-pick labels are processed when the PR is merged
  • Container Builds: Container images are automatically tagged with the PR number
  • Permission Levels: Some commands require approver permissions
  • Auto-verified Users: Certain users have automatic verification and merge privileges

For more information, please refer to the project documentation or contact the maintainers.

@openshift-virtualization-qe-bot
Copy link
Copy Markdown

Clean rebase detected — no code changes compared to previous head (48df81e).

@rnetser
Copy link
Copy Markdown
Collaborator Author

rnetser commented May 6, 2026

/build-and-push-container

@openshift-virtualization-qe-bot-3
Copy link
Copy Markdown
Contributor

New container for quay.io/openshift-cnv/openshift-virtualization-tests:pr-4755 published

1 similar comment
@openshift-virtualization-qe-bot-3
Copy link
Copy Markdown
Contributor

New container for quay.io/openshift-cnv/openshift-virtualization-tests:pr-4755 published

@openshift-virtualization-qe-bot-3
Copy link
Copy Markdown
Contributor

/retest all

Auto-triggered: Files in this PR were modified by merged PR #4756.

Overlapping files

utilities/virt.py

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@scripts/tests_analyzer/pytest_marker_analyzer.py`:
- Around line 2013-2014: The condition in _analyze_single_test_dependencies was
corrected to skip non-Python files and avoid revisiting files (the check using
dep_file and visited was inverted previously), which changes behavior and fixes
a bug that caused Python files to be skipped; update the PR description to
explicitly state this is a behavior-changing bug fix (not just a lint refactor),
explain that the fix is in pytest_marker_analyzer.py within
_analyze_single_test_dependencies and references the dep_file/visited guard, and
call out the impact on transitive dependency traversal and test-impact results
so reviewers give it appropriate scrutiny.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f4b9674e-60e1-45fa-aa27-e90efbefd8ad

📥 Commits

Reviewing files that changed from the base of the PR and between bdafe7b and 86be6fe.

📒 Files selected for processing (33)
  • conftest.py
  • scripts/quarantine_stats/generate_dashboard.py
  • scripts/tests_analyzer/pytest_marker_analyzer.py
  • tests/conftest.py
  • tests/infrastructure/golden_images/update_boot_source/test_ssp_data_sources.py
  • tests/infrastructure/instance_types/test_common_vm_preference.py
  • tests/infrastructure/vm_console_proxy/utils.py
  • tests/install_upgrade_operators/csv/csv_permissions_audit/test_csv_permissions_audit.py
  • tests/install_upgrade_operators/json_patch/test_json_patch_annotation_multiple_updates.py
  • tests/install_upgrade_operators/node_component/utils.py
  • tests/install_upgrade_operators/resource_params/utils.py
  • tests/network/kubemacpool/utils.py
  • tests/network/l2_bridge/libl2bridge.py
  • tests/network/sriov/libsriov.py
  • tests/scale/test_scale_benchmark.py
  • tests/storage/cdi_upload/test_upload_virtctl.py
  • tests/storage/golden_image/test_cached_snapshots.py
  • tests/storage/storage_migration/utils.py
  • tests/storage/test_cdi_resources.py
  • tests/utils.py
  • tests/virt/cluster/common_templates/custom_namespace/utils.py
  • tests/virt/cluster/common_templates/general/test_base_template.py
  • tests/virt/cluster/general/mass_machine_type_transition_tests/test_mass_machine_type_transition.py
  • tests/virt/cluster/migration_and_maintenance/test_evictionstrategy.py
  • tests/virt/node/descheduler/conftest.py
  • tests/virt/node/gpu/vgpu/test_rhel_vm_with_vgpu.py
  • tests/virt/node/high_performance_vm/test_numa.py
  • tests/virt/node/hyperv_support/test_hyperv_features_in_vm.py
  • tests/virt/upgrade/utils.py
  • utilities/infra.py
  • utilities/network.py
  • utilities/storage.py
  • utilities/virt.py

Comment on lines +2013 to 2014
if dep_file in visited or dep_file.suffix != ".py":
continue
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Correct fix — but this is a behavior-changing bug fix, not a lint transformation.

The repaired condition is logically sound:

if dep_file in visited or dep_file.suffix != ".py":
    continue
  • dep_file in visited → prevents re-processing (cycle guard). ✓
  • dep_file.suffix != ".py" → skips non-Python files that cannot carry importable dependencies. ✓

Before this fix, the inverted predicate caused the transitive traversal to skip every Python file and attempt import extraction on non-Python files (.yaml, .json, etc.) — making the 1–2 level import expansion silently a no-op for .py files.

WHY this matters: The PR description asserts all changes are "behavior-preserving mechanical transformations". This change is not. It alters which files are included in _analyze_single_test_dependencies's transitive dependency closure, directly affecting which tests are considered impacted by a PR. Reviewers should be aware this is a correctness fix bundled into the lint PR.

Please update the PR description to call this out explicitly as a bug fix so approvers review it with the appropriate scrutiny.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/tests_analyzer/pytest_marker_analyzer.py` around lines 2013 - 2014,
The condition in _analyze_single_test_dependencies was corrected to skip
non-Python files and avoid revisiting files (the check using dep_file and
visited was inverted previously), which changes behavior and fixes a bug that
caused Python files to be skipped; update the PR description to explicitly state
this is a behavior-changing bug fix (not just a lint refactor), explain that the
fix is in pytest_marker_analyzer.py within _analyze_single_test_dependencies and
references the dep_file/visited guard, and call out the impact on transitive
dependency traversal and test-impact results so reviewers give it appropriate
scrutiny.

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.

5 participants