Example #1
0
// AddObjectsFromPath loads the JSON or YAML file containing Kubernetes API resources
// and adds them to the provided ObjectRetriever.
func AddObjectsFromPath(path string, o ObjectRetriever, decoder runtime.Decoder) error {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}
	data, err = yaml.ToJSON(data)
	if err != nil {
		return err
	}
	obj, err := runtime.Decode(decoder, data)
	if err != nil {
		return err
	}
	if err := o.Add(obj); err != nil {
		return err
	}
	return nil
}
// Based on: https://github.com/openshift/origin/blob/master/pkg/api/compatibility_test.go
//
// TestCompatibility reencodes the input using the codec for the given
// version and checks for the presence of the expected keys and absent
// keys in the resulting JSON.
func TestCompatibility(
	t *testing.T,
	version unversioned.GroupVersion,
	input []byte,
	validator func(obj runtime.Object) field.ErrorList,
	expectedKeys map[string]string,
	absentKeys []string,
) {

	// Decode
	codec := runtime.CodecFor(api.Scheme, version)
	obj, err := runtime.Decode(codec, input)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	// Validate
	errs := validator(obj)
	if len(errs) != 0 {
		t.Fatalf("Unexpected validation errors: %v", errs)
	}

	// Encode
	output, err := runtime.Encode(codec, obj)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	// Validate old and new fields are encoded
	generic := map[string]interface{}{}
	if err := json.Unmarshal(output, &generic); err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}

	hasError := false
	for k, expectedValue := range expectedKeys {
		keys := strings.Split(k, ".")
		if actualValue, ok, err := getJSONValue(generic, keys...); err != nil || !ok {
			t.Errorf("Unexpected error for %s: %v", k, err)
			hasError = true
		} else if !reflect.DeepEqual(expectedValue, fmt.Sprintf("%v", actualValue)) {
			hasError = true
			t.Errorf("Unexpected value for %v: expected %v, got %v", k, expectedValue, actualValue)
		}
	}

	for _, absentKey := range absentKeys {
		keys := strings.Split(absentKey, ".")
		actualValue, ok, err := getJSONValue(generic, keys...)
		if err == nil || ok {
			t.Errorf("Unexpected value found for for key %s: %v", absentKey, actualValue)
			hasError = true
		}
	}

	if hasError {
		printer := new(kubectl.JSONPrinter)
		printer.PrintObj(obj, os.Stdout)
		t.Logf("2: Encoded value: %#v", string(output))
	}
}