Add JSON validation function and tests: implement JSON validity check and comprehensive unit tests for valid/invalid cases

This commit is contained in:
Luis Eduardo Jeréz Girón
2024-08-29 13:01:00 -06:00
parent 4805f574b5
commit 60fd653664
2 changed files with 56 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
package validate
import (
"encoding/json"
)
// JSON validates a JSON string, it returns a boolean indicating whether
// the JSON is valid or not.
func JSON(jsonStr string) bool {
var js json.RawMessage
return json.Unmarshal([]byte(jsonStr), &js) == nil
}
+44
View File
@@ -0,0 +1,44 @@
package validate
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestJSON(t *testing.T) {
validJSON := []string{
`{"name": "John", "age": 30}`,
`{"name": "John", "friends": ["Alice", "Bob"]}`,
`{"items": [{"id": 1, "name": "Item1"}, {"id": 2, "name": "Item2"}]}`,
`{"emptyArray": [], "emptyObject": {}}`,
`{"nullValue": null}`,
`{"booleanTrue": true, "booleanFalse": false}`,
`{"numberInt": 123, "numberFloat": 123.456}`,
`{"string": "Hello, World!"}`,
`{"nested": {"level1": {"level2": {"level3": "value"}}}}`,
`{"escapedString": "This is a quote: \"}"}`,
}
for _, jsonStr := range validJSON {
assert.True(t, JSON(jsonStr), "Expected JSON to be valid: %s", jsonStr)
}
invalidJSON := []string{
`{"name": "John", "age": 30`,
`{"name": "John", "friends": ["Alice", "Bob"}`,
`{"items": [{"id": 1, "name": "Item1"}, {"id": 2, "name": "Item2"]]}`,
`{"unclosedString": "Hello}`,
`{"unexpectedToken": tru}`,
`{"incompleteObject": {}`,
`{name: "John", "age": 30}`,
`{"missingComma": "value1" "value2"}`,
`["mismatch": "value"]`,
`some other thing`,
``,
}
for _, jsonStr := range invalidJSON {
assert.False(t, JSON(jsonStr), "Expected JSON to be invalid: %s", jsonStr)
}
}