diff --git a/audit/audit.go b/audit/audit.go index f6ef14c846c443eee01b2295377b0b2ff6c1790c..20e2937377c3add8caffededea70550a0f98cac8 100644 --- a/audit/audit.go +++ b/audit/audit.go @@ -232,6 +232,20 @@ func CheckToFormatForAuditEvent(changes map[string]any, original any, new any, f if !found { return false } + + defer func() { + if err := recover(); err != nil { + logs.ErrorWithFields(map[string]any{ + "error": err, + "field": field, + "index": index, + "original": fmt.Sprintf("%#v", originalFieldValue), + "new": fmt.Sprintf("%#v", newFieldValue), + }, errors.Error("Failed to format for audit event")) + } + didInsert = false + }() + doGroupSlice := doGroupSliceForAuditEvent(originalStructField) originalFormattedObject := checkToFormatForAuditEvent(originalFieldValue, index) @@ -355,7 +369,7 @@ func checkToFormatForAuditEvent(fieldValue reflect.Value, index int) *string { } else if fieldValue.Kind() == reflect.Slice && fieldValue.Len() > 0 { if index == -1 || - index > fieldValue.Len() { + index >= fieldValue.Len() { return nil } diff --git a/audit/audit_test.go b/audit/audit_test.go index b10fce6717ebfbc9ba78ed55f08eb5f981b81a98..7131768fa15d9a53913c16a366cc3dc1e62f83da 100644 --- a/audit/audit_test.go +++ b/audit/audit_test.go @@ -3,37 +3,43 @@ package audit import ( "encoding/json" "fmt" + "gitlab.bob.co.za/bob-public-utils/bobgroup-go-utils/utils" "testing" + "time" ) +type StringType *string + +type Tag struct { + Name string + Value *string + StrType *StringType +} + type MockObject struct { - Object interface{} + Name *string `json:"name"` + Strings []*string `json:"strings"` + Tags []Tag `json:"tag"` + TimeCreated *time.Time `json:"time_created"` + SingleTagPtr *Tag `json:"single_tag_ptr"` + SingleTag Tag `json:"single_tag"` + StrType *StringType `json:"str_type"` } func TestGetChanges(t *testing.T) { object1 := MockObject{ - Object: MockObject{ - Object: MockObject{ - Object: MockObject{ - Object: MockObject{ - Object: "done", - }, - }, - }, - }, + Strings: []*string{nil}, } object2 := MockObject{ - Object: MockObject{ - Object: MockObject{ - Object: MockObject{ - Object: MockObject{ - Object: "done1", - }, - }, - }, - }, + Name: utils.ValueToPointer("NewName"), + Strings: []*string{utils.ValueToPointer("NewStr1"), utils.ValueToPointer("NewStr2")}, + Tags: []Tag{{"NewTag", utils.ValueToPointer("NewValue"), utils.ValueToPointer(StringType(utils.ValueToPointer("NewStrType")))}}, + TimeCreated: utils.ValueToPointer(time.Now()), + SingleTagPtr: &Tag{"NewSingleTagPtr", utils.ValueToPointer("NewSingleValuePtr"), nil}, + SingleTag: Tag{"NewSingleTag", utils.ValueToPointer("NewSingleValue"), nil}, + StrType: utils.ValueToPointer(StringType(utils.ValueToPointer("NewStrType"))), } changes, err := GetChanges(object1, object2) @@ -41,6 +47,6 @@ func TestGetChanges(t *testing.T) { panic(err) } - result, _ := json.Marshal(changes) - fmt.Println(result) + result, _ := json.MarshalIndent(changes, "", " ") + fmt.Println(string(result)) }