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:
wizardchen
2026-04-08 16:35:02 +08:00
parent 5545b852c8
commit f3635f3135
2 changed files with 40 additions and 1 deletions
+3 -1
View File
@@ -59,7 +59,9 @@ func (j *JSON) UnmarshalJSON(data []byte) error {
if j == nil {
return errors.New("JSON: UnmarshalJSON on nil pointer")
}
*j = JSON(data)
copied := make([]byte, len(data))
copy(copied, data)
*j = JSON(copied)
return nil
}
+37
View File
@@ -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")
}
}