mirror of
https://github.com/eduardolat/pgbackweb.git
synced 2026-05-08 12:39:13 -05:00
Add JSON validation function and tests: implement JSON validity check and comprehensive unit tests for valid/invalid cases
This commit is contained in:
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user