Skip to content

Instantly share code, notes, and snippets.

@converge
Created September 15, 2023 12:56
Show Gist options
  • Save converge/6fbd9bcc1cae408f4fcc11b8e7cc82ea to your computer and use it in GitHub Desktop.
Save converge/6fbd9bcc1cae408f4fcc11b8e7cc82ea to your computer and use it in GitHub Desktop.
package testing
import (
"context"
"fmt"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
dynamicfake "k8s.io/client-go/dynamic/fake"
"testing"
)
type mockResourceInterface struct {
}
//func (mm mockDynamicResourceInterface) Resource() {
//
//}
func simpleNamespace(name string) *unstructured.Unstructured {
return &unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": "v1",
"kind": "Namespace",
"metadata": map[string]interface{}{
"name": name,
},
},
}
}
func TestGet(t *testing.T) {
// Create a mock dynamic interface.
sc := runtime.NewScheme()
_ = corev1.AddToScheme(sc)
//dynamicMocks := DynamicMocks{} // TODO: maybe we need to customize this.
//simpleNamespace("foo")
realInterface := dynamicfake.NewSimpleDynamicClient(sc, simpleNamespace("foo"))
//x := NewMockDynamicInterface(realInterface, dynamicMocks)
mock := NewMockDynamicInterface(realInterface, DynamicMocks{})
// Define a test case.
testName := "example-name"
testOptions := metav1.GetOptions{} // Customize options as needed.
expectedResult := &unstructured.Unstructured{} // Set the expected result.
// Construct a context for the test case.
ctx := &MockDynamicContext{
//InnerInterface: &mockDynamicResourceInterface{}, // Replace with your actual inner dynamic interface.
InnerInterface: mock,
Resource: schema.GroupVersionResource{}, // Replace with the appropriate resource.
}
// Set up the mock behavior for the Get function.
mock.mocks.MockGets = []MockDynamicGet{
func(ctx *MockDynamicContext, name string, options metav1.GetOptions, subresources ...string) (MockHandled, *unstructured.Unstructured, error) {
fmt.Println("---debug---")
fmt.Println("got something")
fmt.Println("---debug---")
if name == testName && options == testOptions {
return Handled, expectedResult, nil
}
return Unhandled, nil, nil
},
}
// Call the Get function to be tested.
result, err := mock.Resource(ctx.Resource).Namespace("").Get(context.TODO(), testName, testOptions)
// Perform assertions to check the result and error.
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if result != expectedResult {
t.Errorf("Unexpected result. Expected %+v, but got %+v", expectedResult, result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment