test(types): add unit test for JSON unmarshalling and validation
- Introduced a new test file for JSON handling to ensure that unmarshalling correctly copies input data. - Validated that the stored JSON remains intact after input mutation, and confirmed successful marshalling of the output. - This test enhances the reliability of JSON operations within the types package.
This commit is contained in:
@@ -59,7 +59,9 @@ func (j *JSON) UnmarshalJSON(data []byte) error {
|
|||||||
if j == nil {
|
if j == nil {
|
||||||
return errors.New("JSON: UnmarshalJSON on nil pointer")
|
return errors.New("JSON: UnmarshalJSON on nil pointer")
|
||||||
}
|
}
|
||||||
*j = JSON(data)
|
copied := make([]byte, len(data))
|
||||||
|
copy(copied, data)
|
||||||
|
*j = JSON(copied)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package types
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestJSONUnmarshalCopiesInput(t *testing.T) {
|
||||||
|
type wrapper struct {
|
||||||
|
Value JSON `json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
|
input := []byte(`{"value":{"generated_questions":[{"id":"q1","question":"今晚吃啥"}]}}`)
|
||||||
|
|
||||||
|
var got wrapper
|
||||||
|
if err := json.Unmarshal(input, &got); err != nil {
|
||||||
|
t.Fatalf("unmarshal failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simulate decoder buffer reuse/caller mutation after UnmarshalJSON returns.
|
||||||
|
for i := range input {
|
||||||
|
input[i] = 'x'
|
||||||
|
}
|
||||||
|
|
||||||
|
if !json.Valid(got.Value) {
|
||||||
|
t.Fatalf("stored JSON became invalid after input mutation: %q", string(got.Value))
|
||||||
|
}
|
||||||
|
|
||||||
|
marshaled, err := json.Marshal(got)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(marshaled) == 0 {
|
||||||
|
t.Fatal("expected marshaled output")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user