Skip to content

[WIP]Add vnic_info metric test for NAD reference change#5090

Closed
OhadRevah wants to merge 8 commits into
RedHatQE:mainfrom
OhadRevah:obs-metrics-nad-swap-vnic-info
Closed

[WIP]Add vnic_info metric test for NAD reference change#5090
OhadRevah wants to merge 8 commits into
RedHatQE:mainfrom
OhadRevah:obs-metrics-nad-swap-vnic-info

Conversation

@OhadRevah

@OhadRevah OhadRevah commented Jun 1, 2026

Copy link
Copy Markdown
Contributor
What this PR does / why we need it:

Implements test_metric_kubevirt_vm_vnic_info_after_nad_swap — verifies that kubevirt_vm_vnic_info and kubevirt_vmi_vnic_info metric labels
update correctly after swapping the VM's secondary network NAD reference and completing the triggered live migration.

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

Based on azhivovk:obs-metrics-nad-ref-vnic-info with vlan_index_number renamed to next_vlan_index_number to match the root conftest fixture in #5072.

jira-ticket:

https://redhat.atlassian.net/browse/CNV-85094

Summary by CodeRabbit

  • New Features

    • Added support for updating VM network attachment definitions with new network references.
    • Enhanced test infrastructure for bridge network and VLAN configuration scenarios.
  • Tests

    • Enabled previously disabled test for VM network attachment definition swap validation.
    • Added comprehensive test fixtures for network configuration and VLAN-based testing.
    • Improved test utilities for network connectivity and configuration validation.

azhivovk added 3 commits May 31, 2026 12:42
These modules have no dependency on test-specific code.
Moving them to libs/net/ makes them importable from any test suite
without cross-package imports.

Assisted-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Asia Khromov <azhivovk@redhat.com>
Add cluster_vlan_iterator() to libs/net/cluster.py.
The underlying VLAN list is read from py_config once via a cached
helper; each call returns a fresh generator so every fixture
invocation starts from the beginning.

Add next_vlan_index_number fixture to tests/conftest.py using this
helper so any test suite can allocate cluster VLANs without
cross-package imports.

Network tests continue to use their own fixture in
tests/network/conftest.py and will be adjusted in a follow-up.

Assisted-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Asia Khromov <azhivovk@redhat.com>
Wait condition helpers use vm.vmi which exists on both
BaseVirtualMachine and VirtualMachineForTests.
Widen the type to VirtualMachine so any subclass can be passed
without a type error.

Assisted-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Asia Khromov <azhivovk@redhat.com>
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@coderabbitai

coderabbitai Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR consolidates test-local helpers into libs/net, globalizes VLAN iteration utilities, provisions reusable bridge and NAD fixtures with automatic VLAN allocation, adds a library-level NAD-swap workflow helper, and enables end-to-end metrics validation for NAD swapping on running VMs.

Changes

Library Migration and NAD Swap Test Enable

Layer / File(s) Summary
Core library additions: VMI types and NAD update helper
libs/net/vmspec.py
Type signatures for wait_for_vmi_condition_status and wait_for_no_vmi_condition narrowed from BaseVirtualMachine to VirtualMachine. New update_nad_references helper deep-copies template networks, rewrites Multus networkName for specified interfaces, applies via vm.set_networks, and polls MigrationRequired condition lifecycle (appear then clear).
Import consolidation: test helpers to libs.net
libs/net/nodenetworkconfigurationpolicy.py, tests/network/libs/cloudinit.py, tests/network/libs/cluster_user_defined_network.py, tests/network/bgp/conftest.py, tests/network/l2_bridge/bandwidth/conftest.py, tests/network/l2_bridge/conftest.py, tests/network/l2_bridge/migration_stuntime/conftest.py, tests/network/l2_bridge/nad_ref_change/conftest.py, tests/network/localnet/conftest.py, tests/network/localnet/ipam/conftest.py, tests/network/localnet/liblocalnet.py
Redirect 13 test imports from tests.network.libs.* to libs.net.* for NodeNetworkConfigurationPolicy, dict_normalization_for_dataclass, and nodenetworkconfigurationpolicy. Remove unused constant imports and narrow conftest imports. No fixture logic or signatures changed.
VLAN iteration utility and main conftest fixtures
tests/utils.py, tests/conftest.py
Add get_vlan_index_number generator to global test utils. Introduce session-scoped vlans_list fixture normalizing py_config["vlans"] to integer list, module-scoped vlan_index_number fixture generating indexes, package-scoped bridge_nncp creating NMState Linux bridge on worker nodes, and module-scoped bridge_nad_a and bridge_nad_b creating VLAN-backed NetworkAttachmentDefinition objects.
Network conftest fixture migration and cleanup
tests/network/conftest.py, tests/network/l2_bridge/conftest.py, tests/network/l2_bridge/nad_ref_change/conftest.py
Remove duplicated vlans_list and vlan_index_number fixtures from network conftest (now global). Delete duplicate bridge_nncp from L2 bridge conftest. Update imports and remove unused constant definitions.
NAD reference test wiring to libs.net
tests/network/l2_bridge/nad_ref_change/test_nad_ref_change.py, tests/network/localnet/nad_ref_change/test_nad_ref_change.py
Redirect update_nad_references imports to libs.net.vmspec. Call sites and test logic remain unchanged; only module source updated.
Network utilities refactoring
tests/network/utils.py, tests/observability/metrics/utils.py
Remove get_vlan_index_number from network utils (now in global tests/utils.py). Add get_destination_ip_address helper to fetch and assert VM IPv4 address. Refactor validate_vnic_info to evaluate and return during polling loop instead of assert after loop; log last mismatch on timeout.
NAD swap metrics test fixtures
tests/observability/metrics/conftest.py
Add VM-spec and observability imports. Define _NAD_SWAP_SECONDARY_IFACE constant. Introduce vm_for_nad_swap_test, post_nad_swap_vm, and expected_vnic_info_after_swap class-scoped fixtures to scaffold NAD-swap workflow with initial bridge NAD attachment and post-swap update validation.
NAD swap metrics test execution
tests/observability/metrics/test_vms_metrics.py
Expand test_metric_kubevirt_vm_vnic_info_after_nad_swap signature to consume swap fixtures and refactored validate_vnic_info. Format metric query with post-swap VM name and validate label/value pairs during polling. Remove __test__ = False disabling flag to enable execution.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Rationale: The PR combines import consolidation (repetitive but low-risk), library helper addition with clear logic (NAD-swap workflow), fixture provisioning (straightforward fixture patterns), and test enabling (validation logic refactor adds modest complexity). Multiple files affected, but changes follow consistent patterns. The update_nad_references implementation and validate_vnic_info refactor merit careful logic review; the import migrations are mechanical.

Possibly related PRs

Suggested labels

new-tests

Suggested reviewers

  • rnetser
  • vsibirsk
  • azhivovk
  • albarker-rh
  • RoniKishner
  • dshchedr
  • nirdothan
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Stp Link Required ✅ Passed No new test files or test functions added—only re-enabled existing function and new fixtures (which don't require STP links per requirements).
Title check ✅ Passed The title '[WIP]Add vnic_info metric test for NAD reference change' clearly describes the main change: adding a test for VM VNIC info metrics after NAD swap, matching the PR objectives.
Description check ✅ Passed The PR description covers what the PR does, which issue it fixes (none explicitly), special notes for reviewers, and a Jira ticket link. All required template sections are present and substantively filled.

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

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

Warning

Review ran into problems

🔥 Problems

Linked repositories: Your configuration references 1 linked repositories, but your current plan allows 0. Analyzed ``, skipped RedHatQE/openshift-virtualization-tests-design-docs.


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.

@OhadRevah OhadRevah changed the title Add vnic_info metric test for NAD reference change [WIP]Add vnic_info metric test for NAD reference change Jun 1, 2026
@openshift-virtualization-qe-bot-5

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
  • myakove
  • rnetser
  • vsibirsk

Reviewers:

  • Anatw
  • EdDev
  • OhadRevah
  • RoniKishner
  • albarker-rh
  • azhivovk
  • dshchedr
  • frenzyfriday
  • hmeir
  • nirdothan
  • orelmisan
  • rlobillo
  • rnetser
  • 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.

Comment thread libs/net/cluster.py Outdated
@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -e

echo "=== Get current PR head SHA ==="
HEAD_SHA=$(gh api repos/RedHatQE/openshift-virtualization-tests/pulls/5090 --jq '.head.sha')
echo "HEAD SHA: $HEAD_SHA"

echo ""
echo "=== Smoke-marked test files ==="
rg -l '`@pytest.mark.smoke`' tests/ --type py || echo "NONE FOUND"

echo ""
echo "=== Gating-marked test files ==="
rg -l '`@pytest.mark.gating`' tests/ --type py || echo "NONE FOUND"

echo ""
echo "=== Callers of cluster_vlan_iterator ==="
rg -n 'cluster_vlan_iterator' --type py || echo "NONE"

echo ""
echo "=== Callers of wait_for_vmi_condition_status / wait_for_no_vmi_condition in tests/ ==="
rg -n 'wait_for_vmi_condition_status\|wait_for_no_vmi_condition' tests/ --type py || echo "NONE"

echo ""
echo "=== update_nad_references callers ==="
rg -n 'update_nad_references' --type py || echo "NONE"

echo ""
echo "=== Post inline comment ==="
gh api \
  --method POST \
  repos/RedHatQE/openshift-virtualization-tests/pulls/5090/comments \
  --field body='**Test Execution Plan**

**Run smoke tests: False**
Verified: `rg -l "`@pytest.mark.smoke`" tests/` returns files only in `tests/storage/` and `tests/virt/`. None of those files or their conftest hierarchy import `cluster_vlan_iterator`, `next_vlan_index_number`, `wait_for_vmi_condition_status`, or `wait_for_no_vmi_condition`. No traceable dependency path exists.

**Run gating tests: False**
Verified: `rg -l "`@pytest.mark.gating`" tests/` returns no files that import or transitively call any modified symbol.

**Affected tests to run**

New test (primary deliverable):
- `tests/observability/metrics/test_vms_metrics.py::TestVmVnicInfo::test_metric_kubevirt_vm_vnic_info_after_nad_swap`

Import-path-only refactors (`libnncp`: `tests.network.libs.*` → `libs.net.*`) — collection verification only (`pytest --collect-only`) for:
- `tests/network/bgp/`
- `tests/network/l2_bridge/`
- `tests/network/localnet/`' \
  --field commit_id="$HEAD_SHA" \
  --field path='libs/net/cluster.py' \
  --field position=3

echo "Done"

Length of output: 10121




🧠 Learnings used
Learnt from: EdDev
Repo: RedHatQE/openshift-virtualization-tests PR: 0
File: :0-0
Timestamp: 2026-04-30T13:42:43.892Z
Learning: In the openshift-virtualization-tests repository, when processing test execution plan requests for PRs that introduce NEW test classes or test files (not just modifications to existing tests), always verify STD-first workflow compliance as part of the analysis: (1) check if the new test class has actual implementation code (assertions, test logic) — if so, it needs a prior STD PR, (2) check if the test file has a module docstring with STP or Jira/RFE link, (3) check if `What this PR does / why we need it:` in the PR description has meaningful content. Flag any violation even when the bot's primary request is only for a test execution plan. These checks should be appended to the test execution plan inline comment.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 0
File: :0-0
Timestamp: 2025-12-16T10:28:54.212Z
Learning: In the openshift-virtualization-tests repository, when determining smoke test impact for test execution plans, only set "Run smoke tests: True" if there is a verified, traceable dependency path from smoke tests to the changed code. Session-scoped fixtures or infrastructure-sounding changes do NOT automatically imply smoke test impact - the dependency chain must be explicitly verified using shell scripts before recommending smoke test execution.

Learnt from: jpeimer
Repo: RedHatQE/openshift-virtualization-tests PR: 0
File: :0-0
Timestamp: 2025-12-22T15:56:00.157Z
Learning: In the openshift-virtualization-tests repository, when responding to test execution plan requests from openshift-virtualization-qe-bot-3, do NOT use "REQUEST_CHANGES" review type if the PR author has already marked the PR as verified (e.g., with `/verified` command). Test execution plans are informational guides, not blocking requirements. Use COMMENT event for informational test plans, or only REQUEST_CHANGES if there are actual code issues that need to be addressed before merging.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 0
File: :0-0
Timestamp: 2025-12-16T14:00:59.076Z
Learning: In the openshift-virtualization-tests repository, when responding to test execution plan requests from openshift-virtualization-qe-bot-3, CodeRabbit must post ONLY an inline review comment on the Files Changed tab and then stop immediately without generating any follow-up comments in the PR discussion thread. No acknowledgment messages, no confirmation of posting, no explanation - silence after posting the inline review equals success. Additional comments create empty/meaningless reviews that clutter the PR.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 0
File: :0-0
Timestamp: 2026-05-29T11:02:22.804Z
Learning: In the RedHatQE/openshift-virtualization-tests repository, version-bump PRs that update the main branch to reference a new CNV release (e.g., "Update project `main` to reference cnv 5.0") do NOT add new test files or test modules. These PRs only update metadata (pyproject.toml, tox.ini, .coderabbit.yaml) and clean up resolved Jira fixtures/markers in existing files. The "Stp Link Required" pre-merge check may incorrectly flag hundreds of "newly added" test files as a false positive due to the base-branch comparison shifting after branching — this should be ignored for such PRs.

Learnt from: azhivovk
Repo: RedHatQE/openshift-virtualization-tests PR: 5039
File: tests/network/l2_bridge/nad_ref_change/lib_helpers.py:1-1
Timestamp: 2026-06-02T21:17:09.602Z
Learning: In RedHatQE/openshift-virtualization-tests, when a PR only relocates functions to shared libraries and updates import paths in test files (no logic change), do NOT flag the callers as requiring full test re-execution. At most, run `pytest --collect-only` to verify the new import paths resolve correctly. Only require full re-execution of caller tests when the moved function's implementation changes behavior.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 3062
File: conftest.py:333-333
Timestamp: 2025-12-16T20:11:03.645Z
Learning: In the openshift-virtualization-tests repository, when determining smoke test impact for changes affecting py_config["os_login_param"], follow this verification methodology: (1) Find all smoke tests: `rg "pytest.mark.smoke" --type=py -B2 | grep "def test_"`, (2) For each smoke test file, search for VM creation patterns: `rg "VirtualMachineForTests|running_vm|VirtualMachineForTestsFromTemplate|wait_for_ssh|check_ssh_connectivity"`, (3) Trace the dependency chain: smoke test → VirtualMachineForTests/running_vm() → wait_for_ssh_connectivity() (default enabled) → vm.login_params property → py_config["os_login_param"][vm.os_flavor], (4) Check utilities/virt.py for login_params usage: `rg "os_login_param|login_params" utilities/virt.py -C3`. Any smoke test creating VMs with default SSH connectivity checks (running_vm with check_ssh_connectivity=True) depends on os_login_param, even if the test doesn't directly reference it.

Learnt from: yossisegev
Repo: RedHatQE/openshift-virtualization-tests PR: 0
File: :0-0
Timestamp: 2026-05-14T14:01:37.353Z
Learning: In the RedHatQE/openshift-virtualization-tests repository, when a PR has the `needs-rebase` label and the pre-merge check reports a large number of "new test_*.py files" (e.g., 300+) that do not match the actual PR diff, this is a false positive caused by the check comparing the entire diverged branch file tree against main rather than just the PR diff. Do not raise STP Link Required or Docstring Coverage violations based on such check results — only flag these if the PR diff itself actually adds new test files or functions lacking docstrings.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 0
File: :0-0
Timestamp: 2026-04-03T18:43:06.192Z
Learning: In `scripts/tests_analyzer/pytest_marker_analyzer.py` in the openshift-virtualization-tests repository, `conftest_resolved=True` is an intentional trade-off: once a conftest pathway is resolved, it stops scanning further dependency paths (including non-conftest ones). Removing this flag causes 21 false positive regressions on 150 PRs (measured). The false negative risk — a 2+ level transitive chain through both conftest and non-conftest paths — is considered theoretical. Do not flag `conftest_resolved=True` as hiding non-conftest dependency paths; this behavior is deliberate and empirically validated.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 4328
File: tests/network/flat_overlay/test_multi_network_policy.py:32-32
Timestamp: 2026-04-14T16:15:36.741Z
Learning: In the RedHatQE/openshift-virtualization-tests repository, when reviewing any PR with "Quarantine" in the title or a `quarantine` label, always verify compliance with docs/QUARANTINE_GUIDELINES.md:
- Category 1 (Product Bug): must use `pytest.mark.jira("CNV-XXXXX", run=False)` — the `pytest_jira` plugin conditionally skips the test when the Jira issue is open. Do NOT suggest replacing this with `xfail`.
- Category 2 (Automation Issue): must use `pytest.mark.xfail(run=False, reason=...)` — pytest itself handles the skip.
Flag any quarantine PR that uses the wrong category marker, is missing a Jira ticket reference, or uses `run=False` in the wrong context. Raising these compliance questions is always appropriate for quarantine PRs, even if the final resolution confirms the marker is correct.

Learnt from: azhivovk
Repo: RedHatQE/openshift-virtualization-tests PR: 4772
File: tests/network/l2_bridge/rhel9_rhel10_cluster/test_connectivity.py:20-22
Timestamp: 2026-05-08T12:31:29.230Z
Learning: In RedHatQE/openshift-virtualization-tests, tests marked with `pytest.mark.mixed_os_nodes` run in a dedicated execution lane for dual-stream (mixed RHCOS 9 + RHCOS 10) cluster scenarios. Do NOT add `pytest.mark.tier3` to these tests — the `mixed_os_nodes` marker already handles both environment filtering and lane selection. This applies to all test files under `tests/` that use the `mixed_os_nodes` marker (e.g., tests/network/l2_bridge/rhel9_rhel10_cluster/test_connectivity.py).

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 4954
File: .flake8:4-4
Timestamp: 2026-06-01T14:00:52.523Z
Learning: In RedHatQE/openshift-virtualization-tests, the smoke-marked test files (tests/storage/cdi_clone/test_clone.py, tests/storage/cdi_upload/test_upload_virtctl.py, tests/virt/cluster/common_templates/rhel/test_rhel_os_support.py, tests/virt/node/general/test_container_disk_vm.py) have traceable dependency paths to utilities/storage.py, utilities/hco.py (wait_for_hco_conditions), utilities/infra.py, and utilities/virt.py via direct imports and via tests/storage/conftest.py. Do not conclude "no smoke dependency path" without verifying these transitive imports.

Learnt from: azhivovk
Repo: RedHatQE/openshift-virtualization-tests PR: 4772
File: tests/network/l2_bridge/rhel9_rhel10_cluster/test_connectivity.py:31-37
Timestamp: 2026-05-08T06:44:12.879Z
Learning: In tests/network/l2_bridge/rhel9_rhel10_cluster/test_connectivity.py and tests/network/localnet/rhel9_rhel10_cluster/test_connectivity.py (dual-stream RHCOS 9/10 migration tests), the incremental/state-coupled test design is intentional and agreed upon in the STD (https://github.com/RedHatQE/openshift-virtualization-tests-design-docs/blob/main/stps/sig-virt/dual-stream-cluster-rhcos9-rhcos10/network.md). Tests are ordered (RHCOS 9 → RHCOS 10 → RHCOS 9) using pytest.mark.incremental, and test_*_to_rhcos9 intentionally relies on the VM already being on RHCOS 10 from the previous test. Do not flag this as a state-coupling issue or suggest making these tests independently runnable.

Learnt from: Anatw
Repo: RedHatQE/openshift-virtualization-tests PR: 4833
File: tests/network/localnet/migration_stuntime/libstuntime.py:16-16
Timestamp: 2026-05-12T14:29:54.803Z
Learning: In RedHatQE/openshift-virtualization-tests, hardcoded `/tmp/` paths used inside guest VMs (e.g., `STUNTIME_PING_LOG_PATH = "/tmp/stuntime-ping.log"` in `tests/network/localnet/migration_stuntime/libstuntime.py`) should not be flagged for Ruff S108 (insecure temp file usage). The path is written inside an isolated, ephemeral guest VM that is torn down after the test — not on the host — so symlink/race-condition attack vectors do not apply. Do not suggest `tempfile.mktemp()` or UUID-suffixed paths for VM-internal file paths in this repo's test infrastructure.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 4701
File: tests/virt/node/general/test_windows_vtpm_bitlocker.py:50-52
Timestamp: 2026-05-03T15:38:12.880Z
Learning: In the RedHatQE/openshift-virtualization-tests repository, do not flag pre-existing code patterns (e.g., nested `if` statements, unnecessary list comprehensions) that are not introduced by the current PR when the PR is a lint cleanup/tooling bump. Such improvements should be deferred to dedicated follow-up PRs. This applies to all Python files under tests/ and utilities/.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 2469
File: utilities/sanity.py:139-142
Timestamp: 2025-11-08T07:36:57.616Z
Learning: In the openshift-virtualization-tests repository, user rnetser prefers to keep refactoring PRs (like PR `#2469`) strictly focused on moving/organizing code into more granular modules without adding new functionality, error handling, or behavioral changes. Such improvements should be handled in separate PRs.

Learnt from: jpeimer
Repo: RedHatQE/openshift-virtualization-tests PR: 3571
File: tests/storage/storage_migration/utils.py:158-167
Timestamp: 2026-01-25T13:18:26.819Z
Learning: In the openshift-virtualization-tests repository, user jpeimer prefers to avoid nitpicky style changes (e.g., removing `.keys()` from dict membership checks) because verifying every change is expensive. Be cautious about suggesting low-impact stylistic improvements that require verification overhead.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 3062
File: conftest.py:333-333
Timestamp: 2025-12-16T15:09:49.597Z
Learning: In the openshift-virtualization-tests repository, when conftest.py or utilities/bitwarden.py changes affect py_config["os_login_param"], smoke test impact must be determined by: (1) finding all smoke tests using `rg "pytest.mark.smoke"`, (2) checking each for VM creation patterns (VirtualMachineForTests, running_vm, VirtualMachineForTestsFromTemplate), (3) tracing whether running_vm is called with default check_ssh_connectivity=True, which accesses vm.login_params property that reads py_config["os_login_param"][vm.os_flavor]. The dependency chain is: smoke test → VM creation → running_vm → wait_for_ssh_connectivity → vm.login_params → os_login_param. Any smoke test creating VMs with SSH connectivity (the default) depends on os_login_param.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 0
File: :0-0
Timestamp: 2025-09-29T19:05:24.987Z
Learning: The test execution plan for PR `#1904` focuses on cluster-type conditional logic where nmstate functionality is bypassed on cloud clusters (Azure/AWS) but fully functional on bare-metal/PSI clusters, requiring different test strategies for each environment type.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 0
File: :0-0
Timestamp: 2025-12-16T14:06:22.391Z
Learning: In the openshift-virtualization-tests repository, when posting test execution plan inline review comments using GitHub API, the full test execution plan content must go in the `comments[].body` field (which appears on Files Changed tab), NOT in the top-level `body` field (which appears in PR discussion thread). The top-level `body` field should be omitted or left empty to avoid posting redundant comments in the PR discussion thread.

Learnt from: CR
Repo: RedHatQE/openshift-virtualization-tests PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-05-18T15:22:26.757Z
Learning: Applies to tests/**/test_*.py : New feature tests must follow the STD-first workflow: (1) STP (Software Test Plan) reviewed and approved, (2) STD (Software Test Description) placeholder tests with docstrings and `__test__ = False` reviewed, (3) Implementation only after STD review. Never submit test implementation without prior STD review.

Learnt from: dshchedr
Repo: RedHatQE/openshift-virtualization-tests PR: 4118
File: utilities/database.py:0-0
Timestamp: 2026-03-17T01:32:13.674Z
Learning: In RedHatQE/openshift-virtualization-tests, maintainer dshchedr prefers CodeRabbit to post targeted inline comments on the Files changed tab for each applicable location rather than aggregating multiple issues into a single discussion thread.

Learnt from: dshchedr
Repo: RedHatQE/openshift-virtualization-tests PR: 4118
File: utilities/database.py:0-0
Timestamp: 2026-03-17T01:32:13.674Z
Learning: In RedHatQE/openshift-virtualization-tests, maintainer dshchedr prefers CodeRabbit to post targeted inline comments on the Files Changed tab at each applicable location rather than aggregating multiple issues into a single PR discussion thread reply.

Learnt from: servolkov
Repo: RedHatQE/openshift-virtualization-tests PR: 1776
File: libs/net/node_network.py:25-31
Timestamp: 2025-08-20T23:43:28.117Z
Learning: In the RedHatQE/openshift-virtualization-tests project, servolkov's team always uses bare metal (BM) clusters with IPv4 setup in their testing environment, making defensive checks for IPv4 data presence potentially redundant in their networking code.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 3371
File: scripts/tests_analyzer/compare_coderabbit_decisions.py:199-289
Timestamp: 2026-01-13T10:06:14.822Z
Learning: In the openshift-virtualization-tests repository, user rnetser prefers to keep pagination loops inline rather than extracting them into generic helper functions when the loops have different URL patterns and unique post-processing logic, as the inline approach improves readability and makes each endpoint's behavior more explicit.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 3228
File: .coderabbit.yaml:30-41
Timestamp: 2026-01-05T10:33:55.037Z
Learning: In the openshift-virtualization-tests repository, user rnetser prefers minimal pre-merge checks in CodeRabbit configuration: only docstrings enforcement (80% threshold) is needed, not title or description checks.

Learnt from: jpeimer
Repo: RedHatQE/openshift-virtualization-tests PR: 1160
File: tests/storage/storage_migration/test_mtc_storage_class_migration.py:165-176
Timestamp: 2025-06-17T07:45:37.776Z
Learning: In the openshift-virtualization-tests repository, user jpeimer prefers explicit fixture parameters over composite fixtures in test methods, even when there are many parameters, as they find this approach more readable and maintainable for understanding test dependencies.

Learnt from: akri3i
Repo: RedHatQE/openshift-virtualization-tests PR: 1210
File: tests/virt/cluster/general/mass_machine_type_transition_tests/conftest.py:24-64
Timestamp: 2025-06-23T19:28:20.281Z
Learning: In OpenShift Virtualization mass machine type transition tests, the machine type glob pattern "pc-q35-rhel8.*.*" is intentionally hard-coded in the kubevirt_api_lifecycle_automation_job as it's used only once for this specific test case, with plans to update it in the future if the job needs to support other machine types.

Learnt from: RoniKishner
Repo: RedHatQE/openshift-virtualization-tests PR: 1411
File: utilities/os_utils.py:246-279
Timestamp: 2025-07-22T17:13:59.166Z
Learning: In the RedHatQE/openshift-virtualization-tests repository, CentOS preferences follow the format "centos-stream<version>" (e.g., "centos-stream9", "centos-stream10"). The generate_instance_type_centos_os_matrix function correctly uses regex to extract numeric versions and constructs the latest version string in the same format as the input preferences for proper comparison.

Learnt from: azhivovk
Repo: RedHatQE/openshift-virtualization-tests PR: 4962
File: tests/network/l2_bridge/nad_ref_change/test_nad_ref_change.py:86-95
Timestamp: 2026-05-27T09:21:14.771Z
Learning: In RedHatQE/openshift-virtualization-tests, when testing NAD live-update behavior in tests/network/l2_bridge/nad_ref_change/, asserting full equality on `lookup_iface_status` results before and after `update_nad_references` is intentional. The test intent is that NO interface field (MAC, name, IPs, or any other) should change as a result of the live NAD reference swap. Do not suggest narrowing the assertion to a subset of fields; full equality is the desired behavior and will correctly fail if the live update causes any unexpected interface metadata change.

Learnt from: azhivovk
Repo: RedHatQE/openshift-virtualization-tests PR: 4962
File: tests/network/l2_bridge/nad_ref_change/test_nad_ref_change.py:89-95
Timestamp: 2026-05-21T13:52:58.266Z
Learning: In the `tests/network/l2_bridge/nad_ref_change/test_nad_ref_change.py` `TestRunningVMLinuxBridgeVlanChange` class (marked `pytest.mark.incremental`), the test `test_vm_state_iface_info_preserved` is intentionally scoped only to verifying VM interface metadata invariance (MAC, name, IPs) after a NAD reference live-update. It does NOT assert that the NAD reference field itself changed in the VM spec, because functional correctness of the NAD switch (i.e., that traffic actually moved to the new VLAN) is validated by the subsequent `test_connectivity` / `test_two_networks` tests. Do not flag missing spec-level assertions inside `test_vm_state_iface_info_preserved`.

Learnt from: azhivovk
Repo: RedHatQE/openshift-virtualization-tests PR: 4578
File: tests/network/l2_bridge/nad_ref_change/test_nad_ref_change.py:64-79
Timestamp: 2026-04-26T11:48:11.694Z
Learning: In `tests/network/l2_bridge/nad_ref_change/test_nad_ref_change.py`, the negative test `test_non_migratable_vm_nad_change_not_applied` uses connectivity-only Expected assertions (not a rejection signal) because the NAD live-update feature does NOT expose a rejection/error signal for non-migratable VMs. The only verifiable outcome is that the VM remains connected to the original network with no connectivity to the target VLAN. Do not flag the absence of a rejection-signal assertion in this test as a defect.

Learnt from: azhivovk
Repo: RedHatQE/openshift-virtualization-tests PR: 4962
File: tests/network/l2_bridge/nad_ref_change/lib_helpers.py:28-39
Timestamp: 2026-05-25T20:37:30.920Z
Learning: In RedHatQE/openshift-virtualization-tests, the established Tier1 pattern for waiting for a NAD reference live-update (via live migration) to complete is: (1) wait_for_vmi_condition(vm, condition="MigrationRequired", status=TRUE) to confirm migration was triggered, then (2) wait_for_vmi_condition_missing_or_false(vm, condition="MigrationRequired") to confirm migration started. There is NO additional wait_for_vmi_condition(vm, condition="Ready", status=TRUE) call after these two. Do not flag the absence of a Ready=True wait as a deficiency — the MigrationRequired-only pattern is intentional and matches Tier1 tests. File: tests/network/l2_bridge/nad_ref_change/lib_helpers.py.

Learnt from: rnetser
Repo: RedHatQE/openshift-virtualization-tests PR: 0
File: :0-0
Timestamp: 2025-09-29T19:05:24.987Z
Learning: For PR `#1904` test execution, the critical validation point is test_connectivity_over_migration_between_localnet_vms which should fail gracefully on cloud clusters but pass on bare-metal/PSI clusters, representing the core nmstate conditional logic functionality.

Learnt from: vamsikrishna-siddu
Repo: RedHatQE/openshift-virtualization-tests PR: 2199
File: tests/storage/test_online_resize.py:108-113
Timestamp: 2025-09-28T14:43:07.181Z
Learning: In the openshift-virtualization-tests repo, PR `#2199` depends on PR `#2139` which adds architecture-specific OS_FLAVOR attributes to the Images.Cirros class (OS_FLAVOR_CIRROS for x86_64/ARM64, OS_FLAVOR_FEDORA for s390x), enabling conditional logic based on the underlying OS flavor in tests.

Learnt from: azhivovk
Repo: RedHatQE/openshift-virtualization-tests PR: 4962
File: tests/network/l2_bridge/nad_ref_change/conftest.py:1-1
Timestamp: 2026-05-27T09:24:04.453Z
Learning: In `tests/network/l2_bridge/nad_ref_change/conftest.py`, the `under_test_vm_two_ifaces` fixture intentionally passes `nad_names=[bridge_nad_a.name, bridge_nad_a.name]` — both secondary interfaces start attached to the **same** NAD (`bridge_nad_a`). This is the deliberate "base state" before the live NAD reference update, as described in the STD. The live swap to `bridge_nad_b` is performed by `update_nad_references` inside the test body, not in the fixture. Do not flag this duplicate NAD name as a bug or typo during code review.

@OhadRevah

Copy link
Copy Markdown
Contributor Author

/verified

All tests pass, build 5580

@albarker-rh

Copy link
Copy Markdown
Contributor

/lgtm

@openshift-virtualization-qe-bot-3

Copy link
Copy Markdown
Contributor

/retest all

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

Overlapping files

tests/utils.py

Move update_nad_references to libs/net/vmspec.py to eliminate identical
copies in tests/utils.py and tests/network/l2_bridge/nad_ref_change/lib_helpers.py.
The function is used by both network and observability team directories,
so it belongs in a shared module per project conventions.

assisted by: claude code claude-opus-4-6
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Signed-off-by: Ohad <orevah@redhat.com>

@coderabbitai coderabbitai Bot left a comment

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.

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 `@libs/net/vmspec.py`:
- Around line 316-321: The code currently masks errors by defaulting networks to
[] and silently skipping unmatched nad_name_by_net keys; instead, fail fast:
remove the "or []" fallback so deepcopy(vm.template_spec.networks) must be
present and raise a clear exception if vm.template_spec.networks is None/empty,
and before mutating, validate that every network.name in the copied networks
exists in nad_name_by_net (raise if any missing) so you don't apply a
destructive/no-op patch; then proceed to update network.multus.networkName, call
vm.set_networks(networks=networks) and wait_for_vmi_condition_status as before.
🪄 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: 39ea1de5-c3a2-4b79-80e0-8444934af42e

📥 Commits

Reviewing files that changed from the base of the PR and between a7fb8e7 and b31abcc.

📒 Files selected for processing (4)
  • libs/net/vmspec.py
  • tests/network/l2_bridge/nad_ref_change/lib_helpers.py
  • tests/network/l2_bridge/nad_ref_change/test_nad_ref_change.py
  • tests/observability/metrics/conftest.py
💤 Files with no reviewable changes (1)
  • tests/network/l2_bridge/nad_ref_change/lib_helpers.py

Comment thread libs/net/vmspec.py Outdated
Signed-off-by: Ohad <orevah@redhat.com>
@openshift-virtualization-qe-bot

Copy link
Copy Markdown

/build-and-push-container

@openshift-virtualization-qe-bot-5

Copy link
Copy Markdown

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

@openshift-virtualization-qe-bot

Copy link
Copy Markdown

/verified

All tests passed for PR #5090.
Job: openshift-virtualization-tests-runner #5598

Execution details
pytest -s -o log_cli=true -m tier2 --jira
Image: openshift-virtualization-tests:pr-5090

@openshift-virtualization-qe-bot-3

Copy link
Copy Markdown
Contributor

@coderabbitai

Test execution plan request details

CRITICAL: You MUST post an inline review comment on the first changed line of the first file.
The inline comment should contain the full Test Execution Plan (smoke decision, gating decision, and specific affected tests).
Do NOT submit a blocking review event (REQUEST_CHANGES/APPROVE).
Post a single inline PR comment on Files Changed (non-blocking COMMENT flow).

As an expert software testing engineer, analyze all modified files in this PR and create a targeted test execution plan.
You will post an inline review comment with the test execution plan on the first changed file.
If you fail to run or post a comment, retry.

Analysis Requirements:

  1. Examine code changes in each modified file

  2. Identify affected code paths, functions, and classes

  3. Analyze pytest-specific elements: fixtures (scope, dependencies), parametrization, markers, conftest changes

  4. Trace test dependencies through imports, shared utilities, fixture inheritance, fixture teardown, and yield from cleanup in conftest

  5. Detect new tests introduced in the PR

  6. Utilities and libs impact (when utilities/ or libs/ changes):
    You MUST use shell scripts (rg, git diff) to trace the full impact.
    Follow these sub-steps in order:

    6a. Identify modified symbols: For each changed file under utilities/ or libs/,
    list every modified function or method.
    Example: git diff HEAD~1 --unified=0 -- utilities/hco.py | grep '^[+-]def '

    6b. Find direct callers: Search tests and conftest for each symbol from 6a.
    Example: rg -l 'get_hco_version' tests/

    6c. Trace fixture teardown and cleanup: Find fixtures that reach
    the modified symbol through yield from or context-manager wrappers.
    Example: rg -l 'yield from.*enable_common_boot|def.*enable_common_boot' tests/

    6d. Trace same-file callers: In each changed file, find other functions
    whose body calls a modified symbol (including code after yield
    in @contextmanager helpers).
    Example: rg 'get_hco_version|enable_common_boot' utilities/hco.py

    6e. Expand transitively: If function A calls modified B, then
    tests/fixtures that call A are affected — even when the test body
    never imports B directly.

    Do NOT limit impact to tests that import the modified symbol only.

  7. Smoke test impact: Intersect the affected set from step 6 with smoke-marked tests.
    Run: rg -l '@pytest.mark.smoke' tests/
    VERIFY the above command returned actual file paths before concluding False.
    Set True if either condition is met:

    • a smoke-marked file appears in the affected set from 6b-6e, OR
    • any conftest.py in the smoke test's parent-directory hierarchy (up to repo root)
      imports or calls a modified utilities/libs symbol — including autouse fixtures
      that depend on modified functions. ALL tests in that directory and below are affected.
      Example check: for each smoke_file, scan dirname(smoke_file)/conftest.py,
      dirname(dirname(smoke_file))/conftest.py, etc. for modified symbol imports
      and autouse fixtures that depend on modified symbols.
  8. Gating test impact: Intersect the affected set from step 6 with gating-marked tests.
    Run: rg -l '@pytest.mark.gating' tests/
    Set True if a gating-marked file also appears in the affected set from 6b-6e.
    Utilities/libs changes often affect gating tests without affecting smoke tests.
    Do NOT stop analysis after concluding Run smoke tests: False.

Output rules:
Do NOT include analysis step numbers (1-8) in your visible output.

Your deliverable:
Your inline informational comment will be based on the following requirements:

Test Execution Plan

  • Run smoke tests: True / False — If True, state the dependency path (test → fixture → changed symbol). True ONLY with a verified path.
  • Run gating tests: True / False — If True, state the dependency path. True if any gating-marked test is in the affected set.
  • Affected tests to run (required when utilities/, libs/, or shared conftest changes — list concrete paths even when smoke is False)

Use these formats:

  • path/to/test_file.py - When the entire test file needs verification
  • path/to/test_file.py::TestClass::test_method - When specific test(s) needed
  • path/to/test_file.py::test_function - When specific test(s) needed
  • -m marker - When a marker covers multiple affected tests (e.g. -m gating only if ALL gating tests in scope need run)
  • Tag each listed test or group with its marker when not obvious, e.g. (gating) or (smoke)

Real test commands (MANDATORY when changes affect session/runtime code):

When the affected code runs at session/collection time (conftest fixtures, pytest plugins,
config hooks, session-scoped setup) or modifies runtime behavior that unit tests mock away,
you MUST include concrete pytest commands the PR author must run on a real cluster
to verify the change works end-to-end. Include:

  • A command for the error/fix path (the scenario the PR fixes)
  • A command for the happy path (regression: the normal case still works)
  • Use lightweight tests (e.g., --collect-only for startup failures,
    a single small test for runtime behavior)
    If the PR only changes test logic (not utilities/libs/conftest), the affected test
    paths themselves serve as the real test commands — no separate section needed.

Example output for a session-startup fix:

**Real tests (cluster required)**
Error path (the fix):
`pytest tests/storage/.../test_foo.py --storage-class-matrix=nonexistent-sc --collect-only`
Expected: ValueError with clear message, not IndexError

Happy path (regression):
`pytest tests/storage/.../test_foo.py --storage-class-matrix=<valid-sc> -k test_bar`
Expected: session starts normally

Guidelines:

  • Include tests affected directly OR via fixture setup/teardown, yield from cleanup, or transitive utility call chains (caller calls modified helper)
  • Use a full file path only if ALL tests in that file require verification
  • Use file path + test name when only specific tests use an affected fixture or utility wrapper (preferred for partial file impact)
  • If a test marker can cover multiple files/tests, provide the marker
  • Balance coverage vs over-testing - Keep descriptions minimal
  • Example: if leaf helper foo() changes, include tests whose fixture teardown calls wrapper bar() where bar() calls foo(), even when the test body only imports an unrelated symbol from the same utilities module

Hardware-Related Checks (SR-IOV, GPU, DPDK):

When PR modifies fixtures for hardware-specific resources:

  • Collection Safety: Fixtures MUST have existence checks (return None when hardware unavailable)
  • Test Plan: MUST verify both WITH and WITHOUT hardware:
    • Run affected tests on cluster WITH hardware
    • Verify collection succeeds on cluster WITHOUT hardware

CRITICAL WORKFLOW COMPLETION RULES:

When responding to this test execution plan request, you MUST follow these rules EXACTLY:

  1. YOUR ONLY DELIVERABLE: Post one non-blocking inline comment containing the test execution plan on the first changed line
  2. THEN STOP IMMEDIATELY - Do NOT generate any additional response
  3. FALLBACK ONLY: If inline comment API calls fail after retrying, post as a regular PR comment
  4. SILENCE = SUCCESS: After successfully submitting the review, your task is complete. No confirmation needed.

ABSOLUTE PROHIBITIONS (violating these creates empty/meaningless reviews):

  • ❌ Do NOT post acknowledgment messages like "Test execution plan posted", "Review posted successfully", "I've successfully posted"
  • ❌ Do NOT mention review IDs, URLs, or confirmation of posting in the PR thread
  • ❌ Do NOT add any follow-up comments after submitting the review
  • ❌ Do NOT reply to confirm task completion
  • ❌ Do NOT explain what you did - just do it and stop

Remember: The pull request review is visible to users. Additional comments are redundant noise.

CRITICAL — Verification rules for smoke and gating decisions:
- For each True decision, you must have traced a concrete path: test file → fixture → utility function → modified symbol.
- Do NOT assume impact based on scope, file proximity, or infrastructure-sounding names.
Only set True when you trace a concrete path through steps 6a-6e, then 7 or 8.
WRONG: "utilities/hco.py changed → run smoke" (no traced dependency path)
WRONG: "Run smoke tests: False" with no affected-test list when gating tests use the changed utility
RIGHT: "Run smoke tests: False, Run gating tests: True" plus tests/.../test_foo.py::TestBar::test_baz (gating)
RIGHT: "Smoke test X uses fixture Y → wrapper Z → changed function W in utilities/hco.py"

Comment thread libs/net/cluster.py Outdated
@coderabbitai

coderabbitai Bot commented Jun 9, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -e

HEAD_SHA=$(gh api repos/RedHatQE/openshift-virtualization-tests/pulls/5090 --jq '.head.sha')
echo "HEAD SHA: $HEAD_SHA"

echo ""
echo "=== Smoke-marked test files ==="
rg -l '`@pytest.mark.smoke`' tests/ --type py || echo "NONE FOUND"

echo ""
echo "=== Gating-marked test files ==="
rg -l '`@pytest.mark.gating`' tests/ --type py || echo "NONE FOUND"

echo ""
echo "=== Callers of cluster_vlan_iterator in tests/ ==="
rg -n 'cluster_vlan_iterator' tests/ --type py || echo "NONE"

echo ""
echo "=== Callers of wait_for_vmi_condition_status / wait_for_no_vmi_condition in tests/ ==="
rg -n 'wait_for_vmi_condition_status\|wait_for_no_vmi_condition' tests/ --type py || echo "NONE"

echo ""
echo "=== update_nad_references callers in tests/ ==="
rg -n 'update_nad_references' tests/ --type py || echo "NONE"

echo ""
echo "=== Post inline comment ==="
gh api \
  --method POST \
  repos/RedHatQE/openshift-virtualization-tests/pulls/5090/comments \
  --field body='**Test Execution Plan**

**Run smoke tests: False**
Verified: `rg -l "`@pytest.mark.smoke`" tests/` returns files only in `tests/storage/` and `tests/virt/`. None of those files or their conftest hierarchy import `cluster_vlan_iterator`, `next_vlan_index_number`, `wait_for_vmi_condition_status`, or `wait_for_no_vmi_condition`. No traceable dependency path exists.

**Run gating tests: False**
Verified: `rg -l "`@pytest.mark.gating`" tests/` returns no files that import or transitively call any modified symbol (`cluster_vlan_iterator`, `wait_for_vmi_condition_status`, `wait_for_no_vmi_condition`, `update_nad_references`).

**Affected tests to run**

New test (primary deliverable of this PR):
- `tests/observability/metrics/test_vms_metrics.py::TestVmVnicInfo::test_metric_kubevirt_vm_vnic_info_after_nad_swap`

Import-path-only refactors (`libnncp`: `tests.network.libs.*` → `libs.net.*`) — collection verification only:

Length of output: 6766


🏁 Script executed:

#!/bin/bash
set -e

echo "=== Check gating tests for next_vlan_index_number ==="
rg -n 'next_vlan_index_number' tests/ --type py || echo "NONE"

echo ""
echo "=== Post inline comment using python to avoid quoting issues ==="
python3 - <<'PYEOF'
import subprocess, json, sys

body = """**Test Execution Plan**

**Run smoke tests: False**
Verified: smoke-marked files are in `tests/storage/` and `tests/virt/`. The `next_vlan_index_number` fixture (module-scope, non-autouse) is only consumed in `tests/observability/metrics/conftest.py`. No smoke test requests it, and no smoke conftest hierarchy imports `cluster_vlan_iterator`. No traceable dependency path.

**Run gating tests: False**
Verified: `next_vlan_index_number` is not used in any gating-marked test. `wait_for_vmi_condition_status`/`wait_for_no_vmi_condition` have zero callers in `tests/`. `update_nad_references` callers (`tests/network/l2_bridge/nad_ref_change/`, `tests/network/localnet/nad_ref_change/`) are not gating-marked. No traceable dependency path.

**Affected tests to run**

New test (primary deliverable of this PR):
- `tests/observability/metrics/test_vms_metrics.py::TestVmVnicInfo::test_metric_kubevirt_vm_vnic_info_after_nad_swap`

Import-path-only refactors (`libnncp`: `tests.network.libs.*` -> `libs.net.*`) — collection verification only (`pytest --collect-only`) for:
- `tests/network/bgp/`
- `tests/network/l2_bridge/`
- `tests/network/localnet/`"""

payload = {
    "body": body,
    "commit_id": "1ea7591a62a5ee1f129f6afe7de1ceafb30df08b",
    "path": "libs/net/cluster.py",
    "position": 3
}

result = subprocess.run(
    ["gh", "api", "--method", "POST",
     "repos/RedHatQE/openshift-virtualization-tests/pulls/5090/comments",
     "--input", "-"],
    input=json.dumps(payload).encode(),
    capture_output=True
)
print("STDOUT:", result.stdout.decode()[:500])
print("STDERR:", result.stderr.decode()[:500])
print("RC:", result.returncode)
PYEOF

Length of output: 3136



coderabbitai[bot]
coderabbitai Bot previously approved these changes Jun 9, 2026

@Anatw Anatw left a comment

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.

Thank you, Ohad!

I stopped the review after the 5th commit. Will continue after the commits are squashed, it is hard to review.

Comment thread tests/observability/metrics/conftest.py Outdated
Comment thread tests/observability/metrics/conftest.py Outdated
Comment thread tests/observability/metrics/conftest.py Outdated
Comment thread tests/observability/metrics/conftest.py Outdated
Comment thread tests/observability/metrics/conftest.py Outdated
Comment thread tests/observability/metrics/conftest.py Outdated
Comment thread tests/observability/metrics/conftest.py Outdated
Comment thread tests/observability/metrics/conftest.py
Comment thread tests/observability/metrics/conftest.py
Comment thread tests/utils.py Outdated
@openshift-virtualization-qe-bot-5

Copy link
Copy Markdown

Clean rebase detected — no code changes compared to previous head (1ea7591).
The following labels were preserved: verified, commented-Anatw, commented-OhadRevah, commented-coderabbitai[bot], lgtm-coderabbitai[bot], commented-openshift-virtualization-qe-bot-3.

@codecov

codecov Bot commented Jun 10, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.65%. Comparing base (a2dc143) to head (f6f23e9).
⚠️ Report is 95 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5090      +/-   ##
==========================================
- Coverage   98.67%   98.65%   -0.02%     
==========================================
  Files          25       25              
  Lines        2487     2461      -26     
==========================================
- Hits         2454     2428      -26     
  Misses         33       33              
Flag Coverage Δ
utilities 98.65% <100.00%> (-0.02%) ⬇️

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

☔ View full report in Codecov by Harness.
📢 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.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tests/observability/metrics/utils.py (1)

601-609: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

HIGH: Order-dependent VNIC validation can fail even when a matching metric exists.

At Line 602, the code validates only result[0]. If Prometheus returns multiple series, the first one may not be the target interface, causing false timeout/failure. Match against any returned metric entry and succeed when one fully matches.

Suggested fix
-            if sample and (result := sample.get("data", {}).get("result")):
-                vnic_info_metric_result = result[0].get("metric")
-                mismatch_vnic_info = {}
-                for info, expected_value in vnic_info_to_compare.items():
-                    actual_value = vnic_info_metric_result.get(info)
-                    if actual_value != expected_value:
-                        mismatch_vnic_info[info] = {f"Expected: {expected_value}", f"Actual: {actual_value}"}
-                if not mismatch_vnic_info:
-                    return
+            if sample and (result := sample.get("data", {}).get("result")):
+                mismatch_vnic_info = None
+                for metric_result in result:
+                    vnic_info_metric_result = metric_result.get("metric", {})
+                    current_mismatch = {}
+                    for info, expected_value in vnic_info_to_compare.items():
+                        actual_value = vnic_info_metric_result.get(info)
+                        if actual_value != expected_value:
+                            current_mismatch[info] = {
+                                f"Expected: {expected_value}",
+                                f"Actual: {actual_value}",
+                            }
+                    if not current_mismatch:
+                        return
+                    mismatch_vnic_info = current_mismatch
🤖 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 `@tests/observability/metrics/utils.py` around lines 601 - 609, The validation
currently inspects only result[0], which is order-dependent; modify the logic
that processes sample.get("data", {}).get("result") to iterate over all entries
in result and for each entry compare its metric (vnic_info_metric_result)
against vnic_info_to_compare, returning early if any entry fully matches; if
none match, build a mismatch_vnic_info (or aggregate per-entry differences) and
proceed with the failure path as before. Ensure you update the loop around
result and keep variable names vnic_info_metric_result, mismatch_vnic_info and
vnic_info_to_compare so the change is localized and easy to review.
tests/observability/metrics/test_vms_metrics.py (1)

47-51: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

HIGH: Fail fast in get_last_transition_time instead of returning implicit None

On Line 48, if status.conditions is missing or READY is absent, this function falls through with implicit None. That delays the real failure until the timeout loop and obscures root cause. Raise immediately with context.

Proposed fix
 def get_last_transition_time(vm):
-    for condition in vm.instance.get("status", {}).get("conditions"):
+    conditions = vm.instance.get("status", {}).get("conditions")
+    if not conditions:
+        raise ValueError(f"VM {vm.name} has no status.conditions")
+
+    for condition in conditions:
         if condition.get("type") == vm.Condition.READY:
             last_transition_time = condition.get("lastTransitionTime")
             return int((datetime.strptime(last_transition_time, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=UTC)).timestamp())
+    raise ValueError(f"VM {vm.name} has no READY condition")

As per coding guidelines: “No defensive programming. Fail-fast and don't hide bugs with fake defaults.” Ruff also flags this path with RET503.

🤖 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 `@tests/observability/metrics/test_vms_metrics.py` around lines 47 - 51, The
get_last_transition_time function currently can return None when
status.conditions is missing or no READY condition is present; change it to fail
fast by explicitly checking that vm.instance.get("status", {}).get("conditions")
exists and is a sequence and raise a ValueError with context if not, then
iterate conditions to find the one where condition.get("type") ==
vm.Condition.READY, parse its "lastTransitionTime" as before and return the
timestamp, and if no READY condition is found raise a ValueError that includes
vm identifying information so the caller sees the real cause instead of getting
an implicit None.

Sources: Coding guidelines, Linters/SAST tools

🤖 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 `@libs/net/vmspec.py`:
- Around line 315-320: The code allows continuing to patch and wait even when
nad_name_by_net is empty; before performing the patch/wait logic (after
computing nad_name_by_net and before using updated_names/networks), add a
fail-fast check: if nad_name_by_net is empty, raise a ValueError (or appropriate
exception) with a clear message including vm.name so the caller gets an
immediate, actionable error instead of a no-op timeout. Locate the logic that
uses nad_name_by_net/updated_names/networks in this function (the block that
computes resource_version, networks, updated_names) and insert the validation
there.

In `@tests/conftest.py`:
- Line 2783: The line assigns bridge using an unchecked access with a forbidden
"# type: ignore"; remove the suppression and make the typing explicit by
retrieving the interface into a properly annotated variable or casting/asserting
its type before accessing .name (e.g., use a typed local like interface:
InterfaceType = bridge_nncp.desired_state_spec.interfaces[0] or use
cast(InterfaceType, bridge_nncp.desired_state_spec.interfaces[0]) and then set
bridge = interface.name), or add a runtime assert to satisfy the type checker;
target the bridge_nncp.desired_state_spec.interfaces[0].name access and the
bridge variable so the fix replaces the ignore with an explicit type
annotation/cast/assert.
- Line 2764: The test fixture accesses hosts_common_available_ports[-1] without
checking for emptiness; update the fixture setup to first guard that
hosts_common_available_ports is non-empty (e.g., if not
hosts_common_available_ports: raise a clear exception or pytest.skip with a
descriptive message) before constructing
libnncp.Port(name=hosts_common_available_ports[-1]); ensure the check is placed
immediately before the port=[libnncp.Port(...)] usage so the failure is fast and
the error message references hosts_common_available_ports and the fixture that
builds the port list.

In `@tests/utils.py`:
- Around line 787-789: The helper get_vlan_index_number lacks type hints and a
docstring: add type annotations (e.g., def get_vlan_index_number(vlans_list:
Sequence[int]) -> Iterator[int]) and import typing names (Sequence, Iterator) as
needed, and add a Google-style docstring explaining that the function yields
VLAN indices from vlans_list one by one and will raise ValueError when the list
is exhausted (include the ValueError message contract and an example of
usage/side effect). Ensure the docstring documents Args, Yields, and Raises
sections and keep the ValueError message consistent with the existing f-string.

---

Outside diff comments:
In `@tests/observability/metrics/test_vms_metrics.py`:
- Around line 47-51: The get_last_transition_time function currently can return
None when status.conditions is missing or no READY condition is present; change
it to fail fast by explicitly checking that vm.instance.get("status",
{}).get("conditions") exists and is a sequence and raise a ValueError with
context if not, then iterate conditions to find the one where
condition.get("type") == vm.Condition.READY, parse its "lastTransitionTime" as
before and return the timestamp, and if no READY condition is found raise a
ValueError that includes vm identifying information so the caller sees the real
cause instead of getting an implicit None.

In `@tests/observability/metrics/utils.py`:
- Around line 601-609: The validation currently inspects only result[0], which
is order-dependent; modify the logic that processes sample.get("data",
{}).get("result") to iterate over all entries in result and for each entry
compare its metric (vnic_info_metric_result) against vnic_info_to_compare,
returning early if any entry fully matches; if none match, build a
mismatch_vnic_info (or aggregate per-entry differences) and proceed with the
failure path as before. Ensure you update the loop around result and keep
variable names vnic_info_metric_result, mismatch_vnic_info and
vnic_info_to_compare so the change is localized and easy to review.
🪄 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: 2031c349-6636-4453-a04f-f726d1fddf59

📥 Commits

Reviewing files that changed from the base of the PR and between b31abcc and 2bf414c.

📒 Files selected for processing (13)
  • libs/net/vmspec.py
  • tests/conftest.py
  • tests/network/conftest.py
  • tests/network/l2_bridge/conftest.py
  • tests/network/l2_bridge/migration_stuntime/conftest.py
  • tests/network/l2_bridge/nad_ref_change/conftest.py
  • tests/network/localnet/liblocalnet.py
  • tests/network/localnet/nad_ref_change/test_nad_ref_change.py
  • tests/network/utils.py
  • tests/observability/metrics/conftest.py
  • tests/observability/metrics/test_vms_metrics.py
  • tests/observability/metrics/utils.py
  • tests/utils.py
💤 Files with no reviewable changes (3)
  • tests/network/conftest.py
  • tests/network/utils.py
  • tests/network/l2_bridge/conftest.py

Comment thread libs/net/vmspec.py
Comment thread tests/conftest.py
Comment thread tests/conftest.py
Comment thread tests/utils.py Outdated
Move update_nad_references to libs/net/vmspec.py to eliminate identical
copies in tests/utils.py, tests/network/l2_bridge/nad_ref_change/lib_helpers.py,
and tests/network/libs/nad_ref.py. The function is used across network and
observability team directories, so it belongs in a shared module.
Also adds fail-fast validation: raises ValueError for missing networks,
non-Multus networks, and unmatched interface names.

assisted by: claude code claude-opus-4-6
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Signed-off-by: Ohad <orevah@redhat.com>
@openshift-virtualization-qe-bot

Copy link
Copy Markdown

/build-and-push-container

@openshift-virtualization-qe-bot

Copy link
Copy Markdown

Verification failed for PR #5090.
The pipeline did not reach the test execution stage.

Execution details
pytest -s -o log_cli=true -m tier2 --jira

@openshift-virtualization-qe-bot

Copy link
Copy Markdown

/build-and-push-container

@openshift-virtualization-qe-bot-2

Copy link
Copy Markdown
Contributor

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

@openshift-virtualization-qe-bot

Copy link
Copy Markdown

/verified

All tests passed for PR #5090.
Job: openshift-virtualization-tests-runner #5638

Execution details
pytest -s -o log_cli=true -m tier2 --jira
Image: openshift-virtualization-tests:pr-5090

@openshift-virtualization-qe-bot-3

Copy link
Copy Markdown
Contributor

@coderabbitai

Test execution plan request details

CRITICAL: You MUST post an inline review comment on the first changed line of the first file.
The inline comment should contain the full Test Execution Plan (smoke decision, gating decision, and specific affected tests).
Do NOT submit a blocking review event (REQUEST_CHANGES/APPROVE).
Post a single inline PR comment on Files Changed (non-blocking COMMENT flow).

As an expert software testing engineer, analyze all modified files in this PR and create a targeted test execution plan.
You will post an inline review comment with the test execution plan on the first changed file.
If you fail to run or post a comment, retry.

Analysis Requirements:

  1. Examine code changes in each modified file

  2. Identify affected code paths, functions, and classes

  3. Analyze pytest-specific elements: fixtures (scope, dependencies), parametrization, markers, conftest changes

  4. Trace test dependencies through imports, shared utilities, fixture inheritance, fixture teardown, and yield from cleanup in conftest

  5. Detect new tests introduced in the PR

  6. Utilities and libs impact (when utilities/ or libs/ changes):
    You MUST use shell scripts (rg, git diff) to trace the full impact.
    Follow these sub-steps in order:

    6a. Identify modified symbols: For each changed file under utilities/ or libs/,
    list every modified function or method.
    Example: git diff HEAD~1 --unified=0 -- utilities/hco.py | grep '^[+-]def '

    6b. Find direct callers: Search tests and conftest for each symbol from 6a.
    Example: rg -l 'get_hco_version' tests/

    6c. Trace fixture teardown and cleanup: Find fixtures that reach
    the modified symbol through yield from or context-manager wrappers.
    Example: rg -l 'yield from.*enable_common_boot|def.*enable_common_boot' tests/

    6d. Trace same-file callers: In each changed file, find other functions
    whose body calls a modified symbol (including code after yield
    in @contextmanager helpers).
    Example: rg 'get_hco_version|enable_common_boot' utilities/hco.py

    6e. Expand transitively: If function A calls modified B, then
    tests/fixtures that call A are affected — even when the test body
    never imports B directly.

    Do NOT limit impact to tests that import the modified symbol only.

  7. Smoke test impact: Intersect the affected set from step 6 with smoke-marked tests.
    Run: rg -l '@pytest.mark.smoke' tests/
    VERIFY the above command returned actual file paths before concluding False.
    Set True if either condition is met:

    • a smoke-marked file appears in the affected set from 6b-6e, OR
    • any conftest.py in the smoke test's parent-directory hierarchy (up to repo root)
      imports or calls a modified utilities/libs symbol — including autouse fixtures
      that depend on modified functions. ALL tests in that directory and below are affected.
      Example check: for each smoke_file, scan dirname(smoke_file)/conftest.py,
      dirname(dirname(smoke_file))/conftest.py, etc. for modified symbol imports
      and autouse fixtures that depend on modified symbols.
  8. Gating test impact: Intersect the affected set from step 6 with gating-marked tests.
    Run: rg -l '@pytest.mark.gating' tests/
    Set True if a gating-marked file also appears in the affected set from 6b-6e.
    Utilities/libs changes often affect gating tests without affecting smoke tests.
    Do NOT stop analysis after concluding Run smoke tests: False.

Output rules:
Do NOT include analysis step numbers (1-8) in your visible output.

Your deliverable:
Your inline informational comment will be based on the following requirements:

Test Execution Plan

  • Run smoke tests: True / False — If True, state the dependency path (test → fixture → changed symbol). True ONLY with a verified path.
  • Run gating tests: True / False — If True, state the dependency path. True if any gating-marked test is in the affected set.
  • Affected tests to run (required when utilities/, libs/, or shared conftest changes — list concrete paths even when smoke is False)

Use these formats:

  • path/to/test_file.py - When the entire test file needs verification
  • path/to/test_file.py::TestClass::test_method - When specific test(s) needed
  • path/to/test_file.py::test_function - When specific test(s) needed
  • -m marker - When a marker covers multiple affected tests (e.g. -m gating only if ALL gating tests in scope need run)
  • Tag each listed test or group with its marker when not obvious, e.g. (gating) or (smoke)

Real test commands (MANDATORY when changes affect session/runtime code):

When the affected code runs at session/collection time (conftest fixtures, pytest plugins,
config hooks, session-scoped setup) or modifies runtime behavior that unit tests mock away,
you MUST include concrete pytest commands the PR author must run on a real cluster
to verify the change works end-to-end. Include:

  • A command for the error/fix path (the scenario the PR fixes)
  • A command for the happy path (regression: the normal case still works)
  • Use lightweight tests (e.g., --collect-only for startup failures,
    a single small test for runtime behavior)
    If the PR only changes test logic (not utilities/libs/conftest), the affected test
    paths themselves serve as the real test commands — no separate section needed.

Example output for a session-startup fix:

**Real tests (cluster required)**
Error path (the fix):
`pytest tests/storage/.../test_foo.py --storage-class-matrix=nonexistent-sc --collect-only`
Expected: ValueError with clear message, not IndexError

Happy path (regression):
`pytest tests/storage/.../test_foo.py --storage-class-matrix=<valid-sc> -k test_bar`
Expected: session starts normally

Guidelines:

  • Include tests affected directly OR via fixture setup/teardown, yield from cleanup, or transitive utility call chains (caller calls modified helper)
  • Use a full file path only if ALL tests in that file require verification
  • Use file path + test name when only specific tests use an affected fixture or utility wrapper (preferred for partial file impact)
  • If a test marker can cover multiple files/tests, provide the marker
  • Balance coverage vs over-testing - Keep descriptions minimal
  • Example: if leaf helper foo() changes, include tests whose fixture teardown calls wrapper bar() where bar() calls foo(), even when the test body only imports an unrelated symbol from the same utilities module

Hardware-Related Checks (SR-IOV, GPU, DPDK):

When PR modifies fixtures for hardware-specific resources:

  • Collection Safety: Fixtures MUST have existence checks (return None when hardware unavailable)
  • Test Plan: MUST verify both WITH and WITHOUT hardware:
    • Run affected tests on cluster WITH hardware
    • Verify collection succeeds on cluster WITHOUT hardware

CRITICAL WORKFLOW COMPLETION RULES:

When responding to this test execution plan request, you MUST follow these rules EXACTLY:

  1. YOUR ONLY DELIVERABLE: Post one non-blocking inline comment containing the test execution plan on the first changed line
  2. THEN STOP IMMEDIATELY - Do NOT generate any additional response
  3. FALLBACK ONLY: If inline comment API calls fail after retrying, post as a regular PR comment
  4. SILENCE = SUCCESS: After successfully submitting the review, your task is complete. No confirmation needed.

ABSOLUTE PROHIBITIONS (violating these creates empty/meaningless reviews):

  • ❌ Do NOT post acknowledgment messages like "Test execution plan posted", "Review posted successfully", "I've successfully posted"
  • ❌ Do NOT mention review IDs, URLs, or confirmation of posting in the PR thread
  • ❌ Do NOT add any follow-up comments after submitting the review
  • ❌ Do NOT reply to confirm task completion
  • ❌ Do NOT explain what you did - just do it and stop

Remember: The pull request review is visible to users. Additional comments are redundant noise.

CRITICAL — Verification rules for smoke and gating decisions:
- For each True decision, you must have traced a concrete path: test file → fixture → utility function → modified symbol.
- Do NOT assume impact based on scope, file proximity, or infrastructure-sounding names.
Only set True when you trace a concrete path through steps 6a-6e, then 7 or 8.
WRONG: "utilities/hco.py changed → run smoke" (no traced dependency path)
WRONG: "Run smoke tests: False" with no affected-test list when gating tests use the changed utility
RIGHT: "Run smoke tests: False, Run gating tests: True" plus tests/.../test_foo.py::TestBar::test_baz (gating)
RIGHT: "Smoke test X uses fixture Y → wrapper Z → changed function W in utilities/hco.py"


from tests.network.libs.apimachinery import dict_normalization_for_dataclass
from libs.net.apimachinery import dict_normalization_for_dataclass

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.

Test Execution Plan

Run smoke tests: False
Verified: smoke-marked files are in tests/storage/, tests/virt/, tests/install_upgrade_operators/, and tests/infrastructure/. None of those files or their conftest hierarchy import cluster_vlan_iterator, next_vlan_index_number, wait_for_vmi_condition_status, wait_for_no_vmi_condition, or update_nad_references. No traceable dependency path.

Run gating tests: False
Verified: gating-marked network test files (tests/network/nmstate/, tests/network/connectivity/, tests/network/localnet/test_default_bridge.py, etc.) have zero imports of any modified symbol. update_nad_references callers (tests/network/l2_bridge/nad_ref_change/, tests/network/localnet/nad_ref_change/) carry no gating marker.

Affected tests to run

New test (primary deliverable of this PR):

  • tests/observability/metrics/test_vms_metrics.py::TestVmVnicInfo::test_metric_kubevirt_vm_vnic_info_after_nad_swap

Import-path-only refactors (libnncp: tests.network.libs.* -> libs.net.*) — collection verification only:

  • pytest --collect-only tests/network/bgp/
  • pytest --collect-only tests/network/l2_bridge/
  • pytest --collect-only tests/network/localnet/

Real tests (cluster required)

tests/conftest.py promotes bridge_nncp (package-scope), bridge_nad_a, bridge_nad_b, vlan_index_number, and vlans_list (session-scope) from per-directory conftest files to the root conftest. These run at session/setup time and must be verified on a real cluster:

Happy path (new observability test end-to-end):
pytest tests/observability/metrics/test_vms_metrics.py::TestVmVnicInfo::test_metric_kubevirt_vm_vnic_info_after_nad_swap -s
Expected: VM starts attached to bridge_nad_a; NAD swap triggers live migration; kubevirt_vm_vnic_info / kubevirt_vmi_vnic_info labels update to reflect bridge_nad_b.

Regression (existing NAD-ref-change tests still collect after fixture relocation):
pytest --collect-only tests/network/l2_bridge/nad_ref_change/ tests/network/localnet/nad_ref_change/
Expected: session collects without import errors; vlan_index_number resolves from tests/conftest.py (moved from tests/network/conftest.py).

@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -e

HEAD_SHA=$(gh api repos/RedHatQE/openshift-virtualization-tests/pulls/5090 --jq '.head.sha')
echo "HEAD SHA: $HEAD_SHA"

echo ""
echo "=== Verify smoke files ==="
rg -l '`@pytest.mark.smoke`' tests/ --type py || echo "NONE FOUND"

echo ""
echo "=== Verify gating files ==="
rg -l '`@pytest.mark.gating`' tests/ --type py || echo "NONE FOUND"

echo ""
echo "=== Callers of wait_for_vmi_condition_status / wait_for_no_vmi_condition in tests/ ==="
rg -n 'wait_for_vmi_condition_status\|wait_for_no_vmi_condition' tests/ --type py || echo "NONE"

echo ""
echo "=== update_nad_references callers ==="
rg -n 'update_nad_references' tests/ --type py || echo "NONE"

echo ""
echo "=== bridge_nncp / vlans_list callers outside conftest ==="
rg -n 'bridge_nncp\|vlans_list\|bridge_nad_a\|bridge_nad_b\|vlan_index_number' tests/ --type py -l || echo "NONE"

echo ""
echo "=== Post inline comment ==="
python3 - <<'PYEOF'
import subprocess, json, sys

HEAD_SHA_RESULT = subprocess.run(
    ["gh", "api", "repos/RedHatQE/openshift-virtualization-tests/pulls/5090", "--jq", ".head.sha"],
    capture_output=True, text=True
)
head_sha = HEAD_SHA_RESULT.stdout.strip()
print(f"Using SHA: {head_sha}")

body = """**Test Execution Plan**

**Run smoke tests: False**
Verified: `rg -l '`@pytest.mark.smoke`' tests/` returns files only in `tests/storage/` and `tests/virt/`. None of those files or their conftest hierarchy import `cluster_vlan_iterator`, `next_vlan_index_number`, `wait_for_vmi_condition_status`, `wait_for_no_vmi_condition`, or `update_nad_references`. No traceable dependency path.

**Run gating tests: False**
Verified: `rg -l '`@pytest.mark.gating`' tests/` returns no files that import or transitively call any modified symbol. `update_nad_references` callers (`tests/network/l2_bridge/nad_ref_change/`, `tests/network/localnet/nad_ref_change/`) carry no gating marker.

**Affected tests to run**

New test (primary deliverable of this PR):
- `tests/observability/metrics/test_vms_metrics.py::TestVmVnicInfo::test_metric_kubevirt_vm_vnic_info_after_nad_swap`

Import-path-only refactors (`libnncp`: `tests.network.libs.*` → `libs.net.*`) — collection verification only:
- `pytest --collect-only tests/network/bgp/`
- `pytest --collect-only tests/network/l2_bridge/`
- `pytest --collect-only tests/network/localnet/`

**Real tests (cluster required)**

`tests/conftest.py` adds new session/package-scoped fixtures (`bridge_nncp`, `bridge_nad_a`, `bridge_nad_b`, `vlan_index_number`, `vlans_list`) that run at collection/setup time. Verify on a real cluster:

Happy path (new fixtures provision correctly):
`pytest tests/observability/metrics/test_vms_metrics.py::TestVmVnicInfo::test_metric_kubevirt_vm_vnic_info_after_nad_swap -s`
Expected: VM starts with `bridge_nad_a`, NAD swap triggers live migration, metric labels update to reflect `bridge_nad_b`.

Regression (existing bridge/VLAN tests still collect and run):
`pytest --collect-only tests/network/l2_bridge/nad_ref_change/`
Expected: session collects without import errors; `vlan_index_number` fixture resolves from `tests/conftest.py` (moved from `tests/network/conftest.py`)."""

payload = {
    "body": body,
    "commit_id": head_sha,
    "path": "libs/net/cluster.py",
    "position": 3
}

result = subprocess.run(
    ["gh", "api", "--method", "POST",
     "repos/RedHatQE/openshift-virtualization-tests/pulls/5090/comments",
     "--input", "-"],
    input=json.dumps(payload).encode(),
    capture_output=True
)
print("STDOUT:", result.stdout.decode()[:800])
print("STDERR:", result.stderr.decode()[:500])
print("RC:", result.returncode)
PYEOF

Length of output: 8439


🏁 Script executed:

#!/bin/bash
set -e

echo "=== PR files sorted ==="
gh api repos/RedHatQE/openshift-virtualization-tests/pulls/5090/files \
  --jq 'sort_by(.filename) | [.[] | {filename: .filename, status: .status, additions: .additions, patch: .patch}]' \
  2>/dev/null

echo ""
echo "=== Check gating network tests for modified symbol imports ==="
rg -n 'cluster_vlan_iterator\|next_vlan_index_number\|wait_for_vmi_condition_status\|wait_for_no_vmi_condition\|update_nad_references\|bridge_nncp\|vlans_list\|bridge_nad_a\|bridge_nad_b\|vlan_index_number' \
  tests/network/nmstate/test_connectivity_after_nmstate_changes.py \
  tests/network/network_service/test_service_config_manifest.py \
  tests/network/user_defined_network/test_user_defined_network.py \
  tests/network/localnet/test_default_bridge.py \
  tests/network/kubemacpool/test_kubemacpool.py \
  tests/network/flat_overlay/test_flat_overlay.py \
  tests/network/connectivity/test_ovs_linux_bridge.py \
  tests/network/connectivity/test_pod_network.py \
  tests/network/migration/test_masquerade_connectivity_after_migration.py 2>/dev/null || echo "NONE"

Length of output: 29120


🏁 Script executed:

#!/bin/bash
python3 - <<'PYEOF'
import subprocess, json

head_sha = "30dbdcd6507f995f4192e44a9702c3e61577cd4c"

body = """**Test Execution Plan**

**Run smoke tests: False**
Verified: smoke-marked files are in `tests/storage/`, `tests/virt/`, `tests/install_upgrade_operators/`, and `tests/infrastructure/`. None of those files or their conftest hierarchy import `cluster_vlan_iterator`, `next_vlan_index_number`, `wait_for_vmi_condition_status`, `wait_for_no_vmi_condition`, or `update_nad_references`. No traceable dependency path.

**Run gating tests: False**
Verified: gating-marked network test files (`tests/network/nmstate/`, `tests/network/connectivity/`, `tests/network/localnet/test_default_bridge.py`, etc.) have zero imports of any modified symbol. `update_nad_references` callers (`tests/network/l2_bridge/nad_ref_change/`, `tests/network/localnet/nad_ref_change/`) carry no gating marker.

**Affected tests to run**

New test (primary deliverable of this PR):
- `tests/observability/metrics/test_vms_metrics.py::TestVmVnicInfo::test_metric_kubevirt_vm_vnic_info_after_nad_swap`

Import-path-only refactors (`libnncp`: `tests.network.libs.*` -> `libs.net.*`) — collection verification only:
- `pytest --collect-only tests/network/bgp/`
- `pytest --collect-only tests/network/l2_bridge/`
- `pytest --collect-only tests/network/localnet/`

**Real tests (cluster required)**

`tests/conftest.py` promotes `bridge_nncp` (package-scope), `bridge_nad_a`, `bridge_nad_b`, `vlan_index_number`, and `vlans_list` (session-scope) from per-directory conftest files to the root conftest. These run at session/setup time and must be verified on a real cluster:

Happy path (new observability test end-to-end):
`pytest tests/observability/metrics/test_vms_metrics.py::TestVmVnicInfo::test_metric_kubevirt_vm_vnic_info_after_nad_swap -s`
Expected: VM starts attached to `bridge_nad_a`; NAD swap triggers live migration; `kubevirt_vm_vnic_info` / `kubevirt_vmi_vnic_info` labels update to reflect `bridge_nad_b`.

Regression (existing NAD-ref-change tests still collect after fixture relocation):
`pytest --collect-only tests/network/l2_bridge/nad_ref_change/ tests/network/localnet/nad_ref_change/`
Expected: session collects without import errors; `vlan_index_number` resolves from `tests/conftest.py` (moved from `tests/network/conftest.py`)."""

# Try libs/net/nodenetworkconfigurationpolicy.py position 6 (the added import line)
payload = {
    "body": body,
    "commit_id": head_sha,
    "path": "libs/net/nodenetworkconfigurationpolicy.py",
    "position": 6
}

result = subprocess.run(
    ["gh", "api", "--method", "POST",
     "repos/RedHatQE/openshift-virtualization-tests/pulls/5090/comments",
     "--input", "-"],
    input=json.dumps(payload).encode(),
    capture_output=True
)
print("STDOUT:", result.stdout.decode()[:800])
print("STDERR:", result.stderr.decode()[:500])
print("RC:", result.returncode)

if result.returncode != 0:
    print("\n--- Retrying with vmspec.py position 1 ---")
    payload2 = {
        "body": body,
        "commit_id": head_sha,
        "path": "libs/net/vmspec.py",
        "position": 1
    }
    result2 = subprocess.run(
        ["gh", "api", "--method", "POST",
         "repos/RedHatQE/openshift-virtualization-tests/pulls/5090/comments",
         "--input", "-"],
        input=json.dumps(payload2).encode(),
        capture_output=True
    )
    print("STDOUT:", result2.stdout.decode()[:800])
    print("STDERR:", result2.stderr.decode()[:500])
    print("RC:", result2.returncode)

    if result2.returncode != 0:
        print("\n--- Retrying with tests/conftest.py position 1 ---")
        payload3 = {
            "body": body,
            "commit_id": head_sha,
            "path": "tests/conftest.py",
            "position": 1
        }
        result3 = subprocess.run(
            ["gh", "api", "--method", "POST",
             "repos/RedHatQE/openshift-virtualization-tests/pulls/5090/comments",
             "--input", "-"],
            input=json.dumps(payload3).encode(),
            capture_output=True
        )
        print("STDOUT:", result3.stdout.decode()[:800])
        print("STDERR:", result3.stderr.decode()[:500])
        print("RC:", result3.returncode)
PYEOF

Length of output: 5107



@azhivovk azhivovk left a comment

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.

The commits are a bit messy but I hope the comments are clear
The main necessary change is to adjust the test to the infra commits I pushed

Comment thread libs/net/vmspec.py
)


def update_nad_references(vm: BaseVirtualMachine, nad_name_by_net: dict[str, str]) -> None:

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.

All defensive checks are redundant - you can use the helper as is
We create the NADs which we use and if there's a problem with resource creation we'll get an API error

Comment thread tests/utils.py
yield vm


def get_vlan_index_number(vlans_list: list[int]) -> Generator[int]:

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.

You can drop the VLAN fixtures changes, we don't need to move it - you can use the new implementation
next(cluster_vlan_ids)

Comment thread tests/conftest.py
@@ -13,6 +13,7 @@
import tempfile

@azhivovk azhivovk Jun 11, 2026

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.

This conftest is messy and carries many unrelated fixtures
@rnetser suggested to create tests/fixtures/<module.py> and use the fixtures as plugins
You can use the NNCP and NADs fixtures in the metrics conftest where you need

@openshift-virtualization-qe-bot

Copy link
Copy Markdown

Successfully removed PR tag: quay.io/openshift-cnv/openshift-virtualization-tests:pr-5090.

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.