From 06865204b4c75efe492b295387701c7cb22e9d10 Mon Sep 17 00:00:00 2001 From: Sohom Bhattacharjee Date: Sun, 30 Jun 2024 19:19:55 +0530 Subject: [PATCH] add tests for json strict unmarshall --- utils/jsonStrictUnmarshall_test.go | 65 ++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 utils/jsonStrictUnmarshall_test.go diff --git a/utils/jsonStrictUnmarshall_test.go b/utils/jsonStrictUnmarshall_test.go new file mode 100644 index 0000000..c49830e --- /dev/null +++ b/utils/jsonStrictUnmarshall_test.go @@ -0,0 +1,65 @@ +package utils + +import ( + "testing" +) + +type Address struct { + Street string `json:"street"` + City string `json:"city"` +} + +type Person struct { + Name string `json:"name"` + Age int `json:"age"` + Address Address `json:"address"` +} + +func TestStrictUnmarshal(t *testing.T) { + validJSON := []byte(`{ + "name": "John Doe", + "age": 30, + "address": { + "street": "123 Main St", + "city": "Anytown" + } + }`) + + invalidJSON := []byte(`{ + "name": "John Doe", + "age": 30, + "address": { + "street": "123 Main St", + "city": "Anytown" + }, + "unknownField": "value" + }`) + + // this json has an unknown field in the inner struct + invalidJSON_2 := []byte(`{ + "name": "John Doe", + "age": 30, + "address": { + "street": "123 Main St", + "city": "Anytown", + "unknownInnerField": "value" + } + }`) + + var person Person + + err := StrictUnmarshal(validJSON, &person) + if err != nil { + t.Errorf("expected no error, got %v", err) + } + + err = StrictUnmarshal(invalidJSON, &person) + if err == nil { + t.Errorf("expected error, got none") + } + + err = StrictUnmarshal(invalidJSON_2, &person) + if err == nil { + t.Errorf("expected error, got none") + } +}