Last active
April 15, 2020 16:38
-
-
Save slok/c5de7f1b31881fb52368f7b77a0cdd15 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package k8sunstructured_test | |
import ( | |
"bytes" | |
"testing" | |
"github.com/stretchr/testify/assert" | |
"github.com/stretchr/testify/require" | |
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/serializer/json" | |
"k8s.io/apimachinery/pkg/runtime/serializer/yaml" | |
) | |
func TestUnstructured(t *testing.T) { | |
tests := map[string]struct { | |
k8sObj string | |
expK8sObj string | |
processObj func(obj runtime.Object) | |
}{ | |
"Check a Service": { | |
k8sObj: ` | |
apiVersion: v1 | |
kind: Service | |
metadata: | |
labels: | |
app: test | |
name: test | |
namespace: test-ns | |
spec: | |
ports: | |
- name: http | |
port: 80 | |
protocol: TCP | |
targetPort: http | |
selector: | |
app: test | |
type: ClusterIP | |
`, | |
expK8sObj: `apiVersion: v1 | |
kind: Service | |
metadata: | |
labels: | |
app: test | |
changed: yep | |
name: test | |
namespace: test-ns | |
spec: | |
ports: | |
- name: http | |
port: 80 | |
protocol: TCP | |
targetPort: http | |
selector: | |
app: test | |
type: ClusterIP | |
`, | |
processObj: func(o runtime.Object) { | |
obj := o.(metav1.Object) | |
labels := obj.GetLabels() | |
labels["changed"] = "yep" | |
obj.SetLabels(labels) | |
}, | |
}, | |
} | |
for name, test := range tests { | |
t.Run(name, func(t *testing.T) { | |
assert := assert.New(t) | |
require := require.New(t) | |
// Decode yaml. | |
dec := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme) | |
obj, _, err := dec.Decode([]byte(test.k8sObj), nil, nil) | |
require.NoError(err) | |
// Process. | |
test.processObj(obj) | |
// Encode object. | |
var b bytes.Buffer | |
enc := json.NewYAMLSerializer(json.DefaultMetaFactory, nil, nil) | |
err = enc.Encode(obj, &b) | |
require.NoError(err) | |
// check | |
assert.Equal(test.expK8sObj, b.String()) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment