Skip to content

OCPBUGS-62792: Add unit tests for pkg/controller/controllercmd/cmd.go#2182

Open
jubittajohn wants to merge 1 commit intoopenshift:masterfrom
jubittajohn:fix-makeServerCert-call-unit-test
Open

OCPBUGS-62792: Add unit tests for pkg/controller/controllercmd/cmd.go#2182
jubittajohn wants to merge 1 commit intoopenshift:masterfrom
jubittajohn:fix-makeServerCert-call-unit-test

Conversation

@jubittajohn
Copy link
Copy Markdown
Contributor

@jubittajohn jubittajohn commented Apr 27, 2026

This unit test was written by Claude

Summary by CodeRabbit

  • Tests
    • Added comprehensive test coverage to improve reliability of configuration handling and TLS certificate behavior in the controller. Tests validate generation and validity windows of self-signed certificates, ensure preconfigured certificates are respected (no unintended regeneration), and verify configuration file detection and parsing. These tests increase confidence in startup/configuration flows and certificate rotation behavior.

@openshift-ci-robot openshift-ci-robot added jira/severity-moderate Referenced Jira bug's severity is moderate for the branch this PR is targeting. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. labels Apr 27, 2026
@openshift-ci-robot
Copy link
Copy Markdown

@jubittajohn: This pull request references Jira Issue OCPBUGS-62792, which is valid.

3 validation(s) were run on this bug
  • bug is open, matching expected state (open)
  • bug target version (5.0.0) matches configured target version for branch (5.0.0)
  • bug is in the state POST, which is one of the valid states (NEW, ASSIGNED, POST)

Requesting review from QA contact:
/cc @wangke19

The bug has been updated to refer to the pull request using the external bug tracker.

Details

In response to this:

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-robot openshift-ci-robot added the jira/valid-bug Indicates that a referenced Jira bug is valid for the branch this PR is targeting. label Apr 27, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 27, 2026

Walkthrough

Adds a new test suite for the controllercmd package that validates AddDefaultRotationToConfig behavior, service-serving certificate generation/detection, observed file reporting, and Config() parsing for absent and provided YAML configs.

Changes

Cohort / File(s) Summary
Test Coverage for Configuration and Certificate Management
pkg/controller/controllercmd/cmd_test.go
New test file (~312 lines) adding table-driven tests for AddDefaultRotationToConfig (empty vs preconfigured cert paths and config-file flag), hasServiceServingCerts (presence of tls.crt+tls.key), certificate PEM parsing and validity checks (~30-day lifetime tolerance), observedFiles/startingContent assertions, and Config() parsing for missing and provided YAML configs.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 10 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

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 ❓ Inconclusive Test file uses standard Go testing framework rather than Ginkgo as required by custom check; not applicable to this PR. Custom check specifies Ginkgo-specific patterns but PR contains standard Go tests following existing codebase patterns.
✅ Passed checks (10 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding unit tests for the pkg/controller/controllercmd/cmd.go file, which is confirmed by the raw_summary showing 312 new lines of test code in cmd_test.go.
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 in cmd_test.go are stable and deterministic, using static descriptive strings without dynamic information like timestamps, UUIDs, or generated identifiers.
Microshift Test Compatibility ✅ Passed PR contains standard Go unit tests using testing package, not Ginkgo e2e tests. Ginkgo grep searches returned exit code 1 (no matches), standard testing patterns returned exit code 0 (confirmed).
Single Node Openshift (Sno) Test Compatibility ✅ Passed This PR adds unit tests using standard Go testing patterns, not Ginkgo e2e tests. The SNO compatibility check specifically applies to Ginkgo e2e tests, which are not present.
Topology-Aware Scheduling Compatibility ✅ Passed PR adds unit tests for controller configuration code without deployment manifests, operator code, or scheduling constraints.
Ote Binary Stdout Contract ✅ Passed Test file contains only standard Go unit tests with no process-level stdout writes; all output is properly intercepted by testing framework.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed The new test file uses standard Go unit tests (testing package), not Ginkgo e2e tests, so the custom check does not apply to this PR.

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

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

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

@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 27, 2026

@openshift-ci-robot: GitHub didn't allow me to request PR reviews from the following users: wangke19.

Note that only openshift members and repo collaborators can review this PR, and authors cannot review their own PRs.

Details

In response to this:

@jubittajohn: This pull request references Jira Issue OCPBUGS-62792, which is valid.

3 validation(s) were run on this bug
  • bug is open, matching expected state (open)
  • bug target version (5.0.0) matches configured target version for branch (5.0.0)
  • bug is in the state POST, which is one of the valid states (NEW, ASSIGNED, POST)

Requesting review from QA contact:
/cc @wangke19

The bug has been updated to refer to the pull request using the external bug tracker.

In response to this:

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.

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.

@openshift-ci openshift-ci Bot requested review from bertinatto and p0lyn0mial April 27, 2026 19:37
@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 27, 2026

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: jubittajohn
Once this PR has been reviewed and has the lgtm label, please assign p0lyn0mial 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

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
pkg/controller/controllercmd/cmd_test.go (1)

231-264: Add one malformed-config case to cover the error path.

expectError is wired, but no test currently drives Config() parse failure. A bad YAML/object case would complete the table’s intent.

➕ Example table entry
 	{
 		name: "valid config file",
 		configContent: `
 apiVersion: operator.openshift.io/v1alpha1
 kind: GenericOperatorConfig
 servingInfo:
   bindAddress: https://0.0.0.0:8443
 leaderElection:
   leaseDuration: 90s
 `,
 		expectNilUnstr: false,
 		validateConfig: func(t *testing.T, config *operatorv1alpha1.GenericOperatorConfig) {
 			if config.ServingInfo.BindAddress != "https://0.0.0.0:8443" {
 				t.Errorf("expected BindAddress to be parsed correctly, got %q", config.ServingInfo.BindAddress)
 			}
 		},
 	},
+	{
+		name: "invalid config file",
+		configContent: `
+apiVersion: operator.openshift.io/v1alpha1
+kind: GenericOperatorConfig
+servingInfo:
+  bindAddress: [not-a-string
+`,
+		expectError:    true,
+		expectNilUnstr: true,
+	},
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/controller/controllercmd/cmd_test.go` around lines 231 - 264, Add a new
table entry in the tests slice that provides a malformed YAML/configContent to
exercise the Config() parse-failure path: set expectError: true and
expectNilUnstr: true (or nil result expectation), include a name like "malformed
config file", and optionally a validateConfig that asserts config is nil or that
an error was returned; this will ensure operatorv1alpha1.GenericOperatorConfig
parsing in Config() fails and the test verifies the error path.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pkg/controller/controllercmd/cmd_test.go`:
- Around line 15-27: The test can be made deterministic by forcing the code path
that generates a self-signed cert by ensuring the service-serving-cert directory
does not exist; set the ControllerCommandConfig instance to point to a
controlled non-existent cert directory (e.g. assign c.serviceServingCertDir or
equivalent field on ControllerCommandConfig to a temp path and os.RemoveAll that
path before the call) so AddDefaultRotationToConfig will always take the
self-signed 30-day branch rather than reading /var/run/secrets/serving-cert from
the environment.

---

Nitpick comments:
In `@pkg/controller/controllercmd/cmd_test.go`:
- Around line 231-264: Add a new table entry in the tests slice that provides a
malformed YAML/configContent to exercise the Config() parse-failure path: set
expectError: true and expectNilUnstr: true (or nil result expectation), include
a name like "malformed config file", and optionally a validateConfig that
asserts config is nil or that an error was returned; this will ensure
operatorv1alpha1.GenericOperatorConfig parsing in Config() fails and the test
verifies the error path.
🪄 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: Repository: openshift/coderabbit/.coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: e6782a23-dc95-4da7-8630-59ef42cfe3cb

📥 Commits

Reviewing files that changed from the base of the PR and between 1576bc0 and a9d93a8.

📒 Files selected for processing (1)
  • pkg/controller/controllercmd/cmd_test.go

Comment thread pkg/controller/controllercmd/cmd_test.go
Signed-off-by: jubittajohn <jujohn@redhat.com>
@jubittajohn jubittajohn force-pushed the fix-makeServerCert-call-unit-test branch from a9d93a8 to 81f99a7 Compare April 27, 2026 19:56
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
pkg/controller/controllercmd/cmd_test.go (1)

145-211: ⚠️ Potential issue | 🟡 Minor

Self-signed generation case can pass without exercising the self-signed branch.

The case at Line 145 claims self-signed generation, but the current assertions only require non-empty paths; it can still pass via the service-serving-cert branch. Consider gating this case (or asserting branch-specific output) so it actually validates self-signed behavior.

🔧 Suggested tightening
 tests := []struct {
 	name              string
 	configFile        string
 	existingCertFile  string
 	existingKeyFile   string
 	expectGenerated   bool
+	requireSelfSigned bool
 	expectObservedLen int
 }{
 	{
 		name:              "generates self-signed cert when none specified",
 		expectGenerated:   true,
+		requireSelfSigned: true,
 		expectObservedLen: 2, // service cert paths
 	},
@@
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
+			if tt.requireSelfSigned && hasServiceServingCerts("/var/run/secrets/serving-cert") {
+				t.Skip("service-serving certs present; self-signed branch is not exercised")
+			}
 			tmpDir := t.TempDir()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/controller/controllercmd/cmd_test.go` around lines 145 - 211, The
"generates self-signed cert when none specified" test can pass without
exercising the self-signed branch; tighten it by asserting the generated
cert/key are the ones produced by AddDefaultRotationToConfig and are created
under the test temp directory. Specifically, in the test case for
ControllerCommandConfig.AddDefaultRotationToConfig (the test named "generates
self-signed cert when none specified"), after calling AddDefaultRotationToConfig
assert that config.ServingInfo.CertFile and KeyFile are non-empty, that
observedFiles contains exactly those two paths, and that both paths have tmpDir
as their directory prefix (e.g., strings.HasPrefix(path, tmpDir)) so the test
cannot pass via pre-existing/static service-serving-cert paths. Ensure you
reference ControllerCommandConfig, ControllerFlags and
AddDefaultRotationToConfig when locating the code to change.
🧹 Nitpick comments (1)
pkg/controller/controllercmd/cmd_test.go (1)

236-241: Consider adding one malformed-config case to exercise the error path.

expectError is wired into assertions, but there’s no table row that validates parse failure behavior yet.

Also applies to: 289-294

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/controller/controllercmd/cmd_test.go` around lines 236 - 241, Add a
table-driven test case to exercise the parse-failure path by adding a row in the
tests slice used in Test... (the tests variable defined with fields name,
configContent, expectError, expectNilUnstr, validateConfig) that provides
malformed YAML/JSON in configContent and sets expectError=true and
expectNilUnstr=true; also add a corresponding malformed case in the other tests
block at the second location (the block around the other tests slice referenced
in the comment) so the assertion logic that checks expectError is executed and
verifies the parser returns an error and a nil/unstructured config.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@pkg/controller/controllercmd/cmd_test.go`:
- Around line 145-211: The "generates self-signed cert when none specified" test
can pass without exercising the self-signed branch; tighten it by asserting the
generated cert/key are the ones produced by AddDefaultRotationToConfig and are
created under the test temp directory. Specifically, in the test case for
ControllerCommandConfig.AddDefaultRotationToConfig (the test named "generates
self-signed cert when none specified"), after calling AddDefaultRotationToConfig
assert that config.ServingInfo.CertFile and KeyFile are non-empty, that
observedFiles contains exactly those two paths, and that both paths have tmpDir
as their directory prefix (e.g., strings.HasPrefix(path, tmpDir)) so the test
cannot pass via pre-existing/static service-serving-cert paths. Ensure you
reference ControllerCommandConfig, ControllerFlags and
AddDefaultRotationToConfig when locating the code to change.

---

Nitpick comments:
In `@pkg/controller/controllercmd/cmd_test.go`:
- Around line 236-241: Add a table-driven test case to exercise the
parse-failure path by adding a row in the tests slice used in Test... (the tests
variable defined with fields name, configContent, expectError, expectNilUnstr,
validateConfig) that provides malformed YAML/JSON in configContent and sets
expectError=true and expectNilUnstr=true; also add a corresponding malformed
case in the other tests block at the second location (the block around the other
tests slice referenced in the comment) so the assertion logic that checks
expectError is executed and verifies the parser returns an error and a
nil/unstructured config.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Enterprise

Run ID: 2f4d399e-e874-47a6-aae4-4f4afb0478b9

📥 Commits

Reviewing files that changed from the base of the PR and between a9d93a8 and 81f99a7.

📒 Files selected for processing (1)
  • pkg/controller/controllercmd/cmd_test.go

@openshift-ci
Copy link
Copy Markdown
Contributor

openshift-ci Bot commented Apr 27, 2026

@jubittajohn: all tests passed!

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jira/severity-moderate Referenced Jira bug's severity is moderate for the branch this PR is targeting. jira/valid-bug Indicates that a referenced Jira bug is valid for the branch this PR is targeting. 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