diff --git a/jsondiff.go b/jsondiff.go index c1eb52d..fdb535a 100644 --- a/jsondiff.go +++ b/jsondiff.go @@ -6,6 +6,7 @@ import ( "fmt" "reflect" "regexp" + "sort" "strings" "github.com/fatih/color" @@ -33,20 +34,27 @@ func CompareJSON(expectedJSON []byte, actualJSON []byte, noise map[string][]stri var actualType interface{} if err := json.Unmarshal(expectedJSON, &expectedType); err != nil { - fmt.Println("Error unmarshalling expected JSON") - return Diff{}, err + return Diff{}, fmt.Errorf("error unmarshalling expected JSON: %v", err) } if err := json.Unmarshal(actualJSON, &actualType); err != nil { - fmt.Println("Error unmarshalling actual JSON") - return Diff{}, err + return Diff{}, fmt.Errorf("error unmarshalling actual JSON: %v", err) } // Check if types of expected and actual JSON are the same. + expectedTypeInfo := reflect.TypeOf(expectedType) + actualTypeInfo := reflect.TypeOf(actualType) + + if expectedTypeInfo == nil { + return Diff{}, fmt.Errorf("invalid type information: expectedType is nil") + } + if actualTypeInfo == nil { + return Diff{}, fmt.Errorf("invalid type information: actualType is nil") + } - if reflect.TypeOf(expectedType) != reflect.TypeOf(actualType) { - expectedJSONString := `Type of expected body: ` + reflect.TypeOf(expectedType).Kind().String() - actualJSONString := `Type of actual body: ` + reflect.TypeOf(actualType).Kind().String() + if expectedTypeInfo != actualTypeInfo { + expectedJSONString := fmt.Sprintf("Type of expected body: %v", expectedTypeInfo.Kind()) + actualJSONString := fmt.Sprintf("Type of actual body: %v", actualTypeInfo.Kind()) offset := []int{4} highlightExpected := color.FgHiRed @@ -862,11 +870,26 @@ func compareAndColorizeMaps(a, b map[string]interface{}, indent string, red, gre func CompareHeaders(expectedHeaders, actualHeaders map[string]string) Diff { var expectAll, actualAll strings.Builder // Builders for the resulting strings. - // Iterate over each key-value pair in the expected map. - for key, expValue := range expectedHeaders { - actValue := actualHeaders[key] // Get the corresponding value from the actual map. + // Get all unique keys from both maps and sort them + keys := make(map[string]bool) + for k := range expectedHeaders { + keys[k] = true + } + for k := range actualHeaders { + keys[k] = true + } + + sortedKeys := make([]string, 0, len(keys)) + for k := range keys { + sortedKeys = append(sortedKeys, k) + } + sort.Strings(sortedKeys) + + // Iterate over sorted keys + for _, key := range sortedKeys { + expValue := expectedHeaders[key] + actValue := actualHeaders[key] - // Calculate the offsets of the differences between the expected and actual values. offsetsStr1, offsetsStr2, _ := diffArrayRange(string(expValue), string(actValue)) // Define colors for highlighting differences.