Skip to content

Conversation

@goruha
Copy link
Contributor

@goruha goruha commented Apr 2, 2025

What

  • Add basic component test
  • Add disabled component test
  • Test component drifting
  • Add any additional use case tests

Why

  • Test basic component features
  • Verify that the component does not create any resources when input enabled: false set
  • Verify that the component does not drift on a second run with the same inputs
  • Add test for any additional than basic use cases for the component

References

Summary by CodeRabbit

  • Tests
    • Enhanced test functionality by integrating dynamic Kubernetes client capabilities.
    • Improved handling of runner resources with a new dynamic informer and timeout mechanism for readiness checks.

@goruha goruha requested review from a team as code owners April 2, 2025 19:40
@coderabbitai
Copy link

coderabbitai bot commented Apr 2, 2025

Walkthrough

This pull request introduces several modifications to the test/component_test.go file. It adds the import of the time package and uncomments multiple Kubernetes-related imports. The namespace variable in the TestBasic method is updated to a new format, and a significant block of code is added to establish a dynamic Kubernetes client configuration. Additionally, a dynamic informer for a custom resource definition related to runners is implemented, which includes logic for handling updates and a timeout mechanism for readiness checks.

Changes

File(s) Change Summary
test/component_test.go Added time package import, uncommented Kubernetes imports, updated namespace format, added dynamic Kubernetes client configuration with error handling, and implemented a dynamic informer for runner CRD with readiness checks.

Poem

I'm a rabbit in a code burrow so bright,
With imports and clients, we take to flight.
Runners now ready, in Kubernetes they play,
Hopping through tests in a seamless ballet.
Each line a leap, each function a cheer,
In the world of code, we have nothing to fear! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@goruha
Copy link
Contributor Author

goruha commented Apr 2, 2025

/terratest

@mergify
Copy link

mergify bot commented Apr 2, 2025

Merge Protections

Your pull request matches the following merge protections and will not be merged until they are valid.

🟢 Require terratest

Wonderful, this rule succeeded.

This rule require terratest status

  • check-success = test/terratest

@goruha
Copy link
Contributor Author

goruha commented Apr 3, 2025

/terratest

1 similar comment
@goruha
Copy link
Contributor Author

goruha commented Apr 3, 2025

/terratest

goruha added 2 commits April 3, 2025 18:26
…s/aws-eks-actions-runner-controller into add-tests

* 'add-tests' of github.com:cloudposse-terraform-components/aws-eks-actions-runner-controller:
  chore: update README.md (#18)
@goruha
Copy link
Contributor Author

goruha commented Apr 3, 2025

/terratest

Copy link

@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 (2)
test/component_test.go (2)

51-51: Fix the typo in the namespace name.
Currently spelled "acttions-runners-%s" instead of "actions-runners-%s". A minor correction ensures consistent naming.

- namespace := fmt.Sprintf("acttions-runners-%s", randomID)
+ namespace := fmt.Sprintf("actions-runners-%s", randomID)

148-151: Use test assertions instead of panic for improved clarity.
Panic will stop test execution abruptly. Consider using require.NoError or assert.FailNow for a standard test failure pattern.

- if err != nil {
-   panic(fmt.Errorf("failed to create dynamic client: %v", err))
- }
+ assert.NoError(s.T(), err, fmt.Sprintf("failed to create dynamic client: %v", err))
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between df3854f and ec1d1ba.

📒 Files selected for processing (1)
  • test/component_test.go (4 hunks)
🧰 Additional context used
🪛 golangci-lint (1.64.8)
test/component_test.go

165-165: Error return value of informer.AddEventHandler is not checked

(errcheck)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Summary
🔇 Additional comments (5)
test/component_test.go (5)

9-9: Import of the 'time' package looks good.
This addition is necessary for timeout handling and appears correctly utilized in the subsequent logic.


20-26: Reintroduced Kubernetes imports are consistent with the new informer logic.
They match the usage below for the dynamic client, GVR, and shared informer factory.


144-146: Configuration check logic is clear and well-handled.
Asserting NoError and NotNil makes sense for verifying the K8S config.


153-158: Defining the Runners CRD GVR looks good.
This matches the custom resource group/version for actions.summerwind.dev.


160-161: Dynamic informer factory creation is correct.
Using corev1.NamespaceAll and a re-sync period of one minute is appropriate for broad-based resource tracking.

@goruha
Copy link
Contributor Author

goruha commented Apr 3, 2025

/terratest

Copy link

@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: 0

♻️ Duplicate comments (1)
test/component_test.go (1)

188-190: ⚠️ Potential issue

Address potential concurrency issue when closing stopChannel.

Multiple update events could attempt to close the channel more than once, leading to a panic. You should implement a safety check before closing the channel.

-			if phase == "Running" && ready == true {
-				close(stopChannel) // Stop the informer if the external secret is ready
+			if phase == "Running" && ready == true {
+				select {
+				case <-stopChannel:
+					// Channel is already closed, prevent panic
+					return
+				default:
+					close(stopChannel) // Stop the informer if the runner is ready
+				}
			}
🧹 Nitpick comments (5)
test/component_test.go (5)

51-51: Fix typo in namespace name.

There appears to be a typo in the namespace name: "acttions-runners-%s" should be "actions-runners-%s".

-	namespace := fmt.Sprintf("acttions-runners-%s", randomID)
+	namespace := fmt.Sprintf("actions-runners-%s", randomID)

149-151: Use consistent error handling pattern.

The error handling approach here (using panic) is inconsistent with the rest of the code that uses assert.NoError. Consider using the same error handling pattern for consistency.

-	if err != nil {
-		panic(fmt.Errorf("failed to create dynamic client: %v", err))
-	}
+	assert.NoError(s.T(), err, "failed to create dynamic client")
+	assert.NotNil(s.T(), dynamicClient)

196-204: Improve resource cleanup in timeout case.

In the timeout case, you're using a defer to close the stopChannel, but this could lead to a panic if the channel was already closed by the event handler. Also, the comment mentions "external secret" which seems out of context.

	select {
		case <-stopChannel:
-			msg := "runner is ready"
+			msg := "Runner is ready"
			fmt.Println(msg)
		case <-time.After(5 * time.Minute):
-			defer close(stopChannel)
+			// Safely close the channel if not already closed
+			select {
+			case <-stopChannel:
+				// Channel is already closed
+			default:
+				close(stopChannel)
+			}
-			msg := "runner is not ready"
+			msg := "Runner is not ready after 5 minutes"
			assert.Fail(s.T(), msg)
	}

160-192: Add error logging for better debugging.

The current error handling for status retrieval only prints to stdout without context. Consider adding more details to the error messages for easier debugging.

			if err != nil || !found {
-				fmt.Println("Error retrieving conditions from status phase")
+				fmt.Printf("Error retrieving phase from runner %s/%s: %v, found: %t\n", 
+					runner.GetNamespace(), runner.GetName(), err, found)
				return
			}
			
			// Similar improvement for the ready status error message
🧰 Tools
🪛 golangci-lint (1.64.8)

165-165: Error return value of informer.AddEventHandler is not checked

(errcheck)


169-172: Improve readability of runner name check.

The current check for the runner name prefixes the message with "runner name is not 'infra-runner'", which can be confusing when the name actually does start with 'infra-runner' but doesn't match for other reasons. Consider making this message more precise.

			if !strings.HasPrefix(runner.GetName(), "infra-runner") || runner.GetNamespace() != namespace {
-				fmt.Printf("runner name is not 'infra-runner', it is '%s'\n", runner.GetName())
+				fmt.Printf("Skipping runner %s/%s (waiting for runner with prefix 'infra-runner' in namespace %s)\n", 
+					runner.GetNamespace(), runner.GetName(), namespace)
				return
			}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ec1d1ba and 4b4fe4a.

📒 Files selected for processing (1)
  • test/component_test.go (4 hunks)
🧰 Additional context used
🪛 golangci-lint (1.64.8)
test/component_test.go

165-165: Error return value of informer.AddEventHandler is not checked

(errcheck)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Summary
🔇 Additional comments (3)
test/component_test.go (3)

165-165: Handle the return value from AddEventHandler.

The static analysis tool indicates that the return value from informer.AddEventHandler is not checked. You should explicitly assign or discard it to address the linter warning.

-	informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
+	_ = informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
🧰 Tools
🪛 golangci-lint (1.64.8)

165-165: Error return value of informer.AddEventHandler is not checked

(errcheck)


144-152: LGTM: Effective implementation of K8s client configuration.

The setup for the Kubernetes client configuration is well-implemented with proper error checking. The dynamic client creation is a good approach for interacting with custom resources.


153-158: LGTM: Correct GroupVersionResource definition for Runners CRD.

The GroupVersionResource definition for the Runners CRD is correctly implemented using the appropriate Group, Version, and Resource names.

@goruha
Copy link
Contributor Author

goruha commented Apr 3, 2025

/terratest

Copy link

@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: 0

♻️ Duplicate comments (1)
test/component_test.go (1)

165-192: ⚠️ Potential issue

Address potential concurrency issue and handle the return from AddEventHandler

  1. Multiple update events could attempt to close the channel more than once, leading to a panic. Use a check or a sync.Once guard before calling close(stopChannel).
  2. The static analysis points out the return from AddEventHandler is not used. You should assign or discard it explicitly.
- informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
+ _ = informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
  UpdateFunc: func(oldObj, newObj interface{}) {
    runner := newObj.(*unstructured.Unstructured)
    ...

    if phase == "Running" && ready == true {
-     close(stopChannel)
+     select {
+     case <-stopChannel:
+       // channel is already closed, prevent panic
+       return
+     default:
+       close(stopChannel)
+     }
    }
  },
})
🧰 Tools
🪛 golangci-lint (1.64.8)

165-165: Error return value of informer.AddEventHandler is not checked

(errcheck)

🧹 Nitpick comments (1)
test/component_test.go (1)

207-209: Consider documenting the purpose of the 5-minute sleep

The long 5-minute sleep after confirming the runner is ready is without explanation. Consider adding a comment explaining why this sleep is necessary (e.g., waiting for GitHub API propagation, ensuring runner stability before verification).

- // Adding a 5 minutes sleep
+ // Sleep for 5 minutes to ensure the runner registration is fully propagated 
+ // to GitHub's API and is stable before verifying with the GitHub client
  time.Sleep(5 * time.Minute)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4b4fe4a and de3d9cc.

📒 Files selected for processing (1)
  • test/component_test.go (4 hunks)
🧰 Additional context used
🪛 golangci-lint (1.64.8)
test/component_test.go

165-165: Error return value of informer.AddEventHandler is not checked

(errcheck)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Summary
🔇 Additional comments (5)
test/component_test.go (5)

9-9: Appropriate imports uncommented for Kubernetes client integration

The uncommented imports are now properly utilized for the Kubernetes client setup and resource monitoring.

Also applies to: 20-26


51-51: Namespace correctly updated to match component purpose

The namespace format has been properly updated from "external-secrets-%s" to "actions-runners-%s" to better reflect the component being tested.


144-152: Well-structured Kubernetes client configuration

The setup of the Kubernetes client configuration and dynamic client is well-implemented with proper error handling.


153-162: GroupVersionResource and informer setup looks good

The definition of the Runners CRD GroupVersionResource and informer factory setup follows best practices.


194-204: Well-structured informer execution with timeout

The approach of running the informer with a stop channel and timeout mechanism is appropriate. The timeout of 5 minutes is reasonable for waiting for a runner to be ready in a test environment.

@goruha goruha merged commit e957859 into main Apr 3, 2025
19 checks passed
@goruha goruha deleted the add-tests branch April 3, 2025 19:33
@goruha goruha linked an issue Apr 3, 2025 that may be closed by this pull request
4 tasks
@github-actions
Copy link

These changes were released in v1.536.0.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add component tests

2 participants