github.com/anthropics/anthropic-sdk-go@v1.70.1/packages/param/null_test.go (about)

     1  package param_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"github.com/anthropics/anthropic-sdk-go/packages/param"
     6  	"testing"
     7  )
     8  
     9  type Nullables struct {
    10  	Slice []int          `json:"slice,omitzero"`
    11  	Map   map[string]int `json:"map,omitzero"`
    12  	param.APIObject
    13  }
    14  
    15  func (n Nullables) MarshalJSON() ([]byte, error) {
    16  	type shadow Nullables
    17  	return param.MarshalObject(n, (*shadow)(&n))
    18  }
    19  
    20  func TestNullMarshal(t *testing.T) {
    21  	bytes, err := json.Marshal(Nullables{})
    22  	if err != nil {
    23  		t.Fatalf("json error %v", err.Error())
    24  	}
    25  	if string(bytes) != `{}` {
    26  		t.Fatalf("expected empty object, got %s", string(bytes))
    27  	}
    28  
    29  	obj := Nullables{
    30  		Slice: param.NullSlice[[]int](),
    31  		Map:   param.NullMap[map[string]int](),
    32  	}
    33  	bytes, err = json.Marshal(obj)
    34  
    35  	if !param.IsNull(obj.Slice) {
    36  		t.Fatal("failed null check")
    37  	}
    38  	if !param.IsNull(obj.Map) {
    39  		t.Fatal("failed null check")
    40  	}
    41  
    42  	if err != nil {
    43  		t.Fatalf("json error %v", err.Error())
    44  	}
    45  	exp := `{"slice":null,"map":null}`
    46  	if string(bytes) != exp {
    47  		t.Fatalf("expected %s, got %s", exp, string(bytes))
    48  	}
    49  }