Skip to content

MCO-2153: Add drift protection tests for NetworkPolicies#6155

Open
HarshwardhanPatil07 wants to merge 1 commit into
openshift:mainfrom
HarshwardhanPatil07:mco-2153-network-policy-drift
Open

MCO-2153: Add drift protection tests for NetworkPolicies#6155
HarshwardhanPatil07 wants to merge 1 commit into
openshift:mainfrom
HarshwardhanPatil07:mco-2153-network-policy-drift

Conversation

@HarshwardhanPatil07

@HarshwardhanPatil07 HarshwardhanPatil07 commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Add unit tests verifying that user modifications and deletions of NetworkPolicies are reverted by the sync loop:

  • DriftProtection: manual spec modification is reverted on resync
  • Idempotent: repeated syncs produce stable policy count
  • DeletionRecreation: single policy deletion triggers re-creation
  • AllDeletedRecreation: bulk deletion of all static policies
  • MOBDeletionRecreation: conditional MOB policy deletion

- What I did

  • Added drift protection unit tests for MCO NetworkPolicies in a dedicated test file (network_policy_drift_test.go).

- How to verify it

- Description for the changelog

Summary by CodeRabbit

  • Tests
    • Added comprehensive test coverage for network policy management, verifying drift protection, idempotency, and proper recovery from policy deletions to ensure system reliability and stability.

Add unit tests verifying that user modifications and deletions of
NetworkPolicies are reverted by the sync loop:

- DriftProtection: manual spec modification is reverted on resync
- Idempotent: repeated syncs produce stable policy count
- DeletionRecreation: single policy deletion triggers re-creation
- AllDeletedRecreation: bulk deletion of all static policies
- MOBDeletionRecreation: conditional MOB policy deletion

Signed-off-by: HarshwardhanPatil07 <harshpat@redhat.com>
@openshift-merge-bot

Copy link
Copy Markdown
Contributor

Pipeline controller notification
This repo is configured to use the pipeline controller. Second-stage tests will be triggered either automatically or after lgtm label is added, depending on the repository configuration. The pipeline controller will automatically detect which contexts are required and will utilize /test Prow commands to trigger the second stage.

For optional jobs, comment /test ? to see a list of all defined jobs. To trigger manually all jobs from second stage use /pipeline required command.

This repository is configured in: LGTM mode

@openshift-ci-robot openshift-ci-robot added the jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. label Jun 8, 2026
@openshift-ci-robot

openshift-ci-robot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

@HarshwardhanPatil07: This pull request references MCO-2153 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "5.0.0" version, but no target version was set.

Details

In response to this:

Add unit tests verifying that user modifications and deletions of NetworkPolicies are reverted by the sync loop:

  • DriftProtection: manual spec modification is reverted on resync
  • Idempotent: repeated syncs produce stable policy count
  • DeletionRecreation: single policy deletion triggers re-creation
  • AllDeletedRecreation: bulk deletion of all static policies
  • MOBDeletionRecreation: conditional MOB policy deletion

- What I did

  • Added drift protection unit tests for MCO NetworkPolicies in a dedicated test file (network_policy_drift_test.go).

- How to verify it

- Description for the changelog

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@openshift-ci openshift-ci Bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jun 8, 2026
@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown

Walkthrough

This PR introduces a new test file network_policy_drift_test.go with five test functions covering different behaviors of the syncNetworkPolicies function. Tests validate drift protection by verifying ingress rule restoration, idempotency by checking stable NetworkPolicy counts across repeated syncs, and recreation scenarios when policies are deleted individually or in bulk.

Changes

NetworkPolicy sync behavior tests

Layer / File(s) Summary
syncNetworkPolicies behavior test suite
pkg/operator/network_policy_drift_test.go
Five test functions verify syncNetworkPolicies behavior: drift protection restores deleted ingress rules, idempotency maintains stable policy counts (3 baseline policies), single-policy deletion and recreation validates PodSelector labels/ingress ports/egress rules, all-policy deletion recreation ensures static policy names are restored, and MOB policy recreation handles deletion in layered pool configurations.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 13 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Test Structure And Quality ⚠️ Warning Tests call undefined helpers (testOperatorForNetworkPolicies, listNetworkPolicies, findPolicy, layeredPool). Missing cleanup, context timeouts, and assertion messages. Implement missing helpers. Add cleanup for cluster resources. Use context timeouts. Add meaningful failure messages to all assertions.
✅ Passed checks (13 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
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.
Stable And Deterministic Test Names ✅ Passed All test names are static and deterministic with no dynamic values (timestamps, UUIDs, pod/namespace names, IP addresses). Test uses standard Go testing framework.
Microshift Test Compatibility ✅ Passed Tests are standard Go unit tests (func Test*(t *testing.T)), not Ginkgo e2e tests. Custom check applies only to Ginkgo tests with It(), Describe(), etc.
Single Node Openshift (Sno) Test Compatibility ✅ Passed The PR adds standard Go unit tests, not Ginkgo e2e tests. SNO compatibility check applies only to Ginkgo tests with Describe/Context/When/It patterns.
Topology-Aware Scheduling Compatibility ✅ Passed PR adds only unit tests for NetworkPolicy drift protection; no scheduling constraints, deployment specs, pod affinity rules, node selectors, or topology-aware logic are introduced.
Ote Binary Stdout Contract ✅ Passed Test file contains no process-level code; only package declaration, imports, and 5 test functions with standard assertions—no stdout writes detected.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed Tests added are standard Go unit tests (using testing package, not Ginkgo), with no IPv4 assumptions, no hardcoded IP addresses, no external connectivity, and no IPv4-specific network policies.
No-Weak-Crypto ✅ Passed The test file contains no weak cryptography (MD5, SHA1, DES, RC4, 3DES, Blowfish, ECB), custom crypto, or non-constant-time secret comparisons.
Container-Privileges ✅ Passed PR adds only a Go test file (network_policy_drift_test.go) with no Kubernetes manifests, container specs, or privileged container settings.
No-Sensitive-Data-In-Logs ✅ Passed No logging statements found in the new test file. Only test assertions access non-sensitive NetworkPolicy configuration data (metadata, ports, labels).
Title check ✅ Passed The title clearly and specifically summarizes the main change—adding drift protection tests for NetworkPolicies—which directly matches the changeset's core purpose of introducing new integration-style unit tests for validating NetworkPolicy sync behavior.

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

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

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.

@openshift-ci

openshift-ci Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: HarshwardhanPatil07
Once this PR has been reviewed and has the lgtm label, please assign rishabhsaini for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
pkg/operator/network_policy_drift_test.go (1)

22-23: 💤 Low value

Consider using context.Background() instead of context.TODO().

While context.TODO() is acceptable in test code, using context.Background() would be more semantically correct for test operations that don't require a specific parent context. Alternatively, consider context.WithTimeout() to prevent tests from hanging if operations block unexpectedly.

♻️ Example refactor
-	policy, err := optr.kubeClient.NetworkingV1().NetworkPolicies(ctrlcommon.MCONamespace).Get(
-		context.TODO(), "allow-machine-config-operator", metav1.GetOptions{})
+	ctx := context.Background()
+	policy, err := optr.kubeClient.NetworkingV1().NetworkPolicies(ctrlcommon.MCONamespace).Get(
+		ctx, "allow-machine-config-operator", metav1.GetOptions{})

Or with timeout:

+	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+	defer cancel()
 	policy, err := optr.kubeClient.NetworkingV1().NetworkPolicies(ctrlcommon.MCONamespace).Get(
-		context.TODO(), "allow-machine-config-operator", metav1.GetOptions{})
+		ctx, "allow-machine-config-operator", metav1.GetOptions{})

Also applies to: 27-28, 31-32, 39-40

🤖 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 `@pkg/operator/network_policy_drift_test.go` around lines 22 - 23, Replace the
use of context.TODO() in the network policy test calls with a more appropriate
context: use context.Background() for simple test operations or, preferably,
context.WithTimeout() to bound RPCs and avoid hangs; update the Get calls on
optr.kubeClient.NetworkingV1().NetworkPolicies(...).Get (and the other
occurrences flagged around the same test) to accept the new context and ensure
any created timeout contexts are canceled (defer cancel()) where applicable.
🤖 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.

Nitpick comments:
In `@pkg/operator/network_policy_drift_test.go`:
- Around line 22-23: Replace the use of context.TODO() in the network policy
test calls with a more appropriate context: use context.Background() for simple
test operations or, preferably, context.WithTimeout() to bound RPCs and avoid
hangs; update the Get calls on
optr.kubeClient.NetworkingV1().NetworkPolicies(...).Get (and the other
occurrences flagged around the same test) to accept the new context and ensure
any created timeout contexts are canceled (defer cancel()) where applicable.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: openshift/coderabbit/.coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: da9ed0f2-3717-4b11-b368-0a76f5d6d6b7

📥 Commits

Reviewing files that changed from the base of the PR and between 4412c7c and 65c5786.

📒 Files selected for processing (1)
  • pkg/operator/network_policy_drift_test.go

@openshift-ci

openshift-ci Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

@HarshwardhanPatil07: The following tests failed, say /retest to rerun all failed tests or /retest-required to rerun all mandatory failed tests:

Test name Commit Details Required Rerun command
ci/prow/unit 65c5786 link true /test unit
ci/prow/verify 65c5786 link true /test verify

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

@HarshwardhanPatil07

HarshwardhanPatil07 commented Jun 12, 2026

Copy link
Copy Markdown
Contributor Author

/retitle MCO-2153: Add drift protection tests for NetworkPolicies

@openshift-ci openshift-ci Bot changed the title (WIP) MCO-2153: Add drift protection tests for NetworkPolicies MCO-2153: Add drift protection tests for NetworkPolicies Jun 12, 2026
@openshift-ci openshift-ci Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jun 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jira/valid-reference Indicates that this PR references a valid Jira ticket of any type.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants