package dataext import ( "encoding/json" "testing" ) func TestJsonOpt_NewAndEmpty(t *testing.T) { o := NewJsonOpt[int](42) if !o.IsSet() { t.Fatal("expected IsSet=true") } if o.IsUnset() { t.Fatal("expected IsUnset=false") } e := EmptyJsonOpt[int]() if e.IsSet() { t.Fatal("expected IsSet=false") } if !e.IsUnset() { t.Fatal("expected IsUnset=true") } } func TestJsonOpt_Value(t *testing.T) { o := NewJsonOpt[string]("hello") v, ok := o.Value() if !ok || v != "hello" { t.Fatalf("got (%q,%v)", v, ok) } e := EmptyJsonOpt[string]() v, ok = e.Value() if ok || v != "" { t.Fatalf("empty got (%q,%v)", v, ok) } } func TestJsonOpt_ValueOrNil(t *testing.T) { o := NewJsonOpt[int](7) p := o.ValueOrNil() if p == nil || *p != 7 { t.Fatalf("expected ptr to 7") } e := EmptyJsonOpt[int]() if e.ValueOrNil() != nil { t.Fatal("expected nil") } } func TestJsonOpt_ValueDblPtrOrNil(t *testing.T) { o := NewJsonOpt[int](7) p := o.ValueDblPtrOrNil() if p == nil || *p == nil || **p != 7 { t.Fatalf("expected double ptr to 7") } e := EmptyJsonOpt[int]() if e.ValueDblPtrOrNil() != nil { t.Fatal("expected nil") } } func TestJsonOpt_MustValue(t *testing.T) { o := NewJsonOpt[int](9) if o.MustValue() != 9 { t.Fatal("MustValue wrong") } defer func() { if recover() == nil { t.Fatal("expected panic") } }() EmptyJsonOpt[int]().MustValue() } func TestJsonOpt_IfSet(t *testing.T) { called := false NewJsonOpt[int](1).IfSet(func(v int) { called = true if v != 1 { t.Fatalf("v=%d", v) } }) if !called { t.Fatal("IfSet did not invoke fn") } called = false EmptyJsonOpt[int]().IfSet(func(v int) { called = true }) if called { t.Fatal("IfSet invoked fn on empty") } } func TestJsonOpt_MarshalJSON(t *testing.T) { o := NewJsonOpt[int](5) b, err := json.Marshal(o) if err != nil { t.Fatal(err) } if string(b) != "5" { t.Fatalf("got %s", b) } e := EmptyJsonOpt[int]() b, err = json.Marshal(e) if err != nil { t.Fatal(err) } if string(b) != "null" { t.Fatalf("got %s", b) } } func TestJsonOpt_UnmarshalJSON(t *testing.T) { var o JsonOpt[int] if err := json.Unmarshal([]byte("42"), &o); err != nil { t.Fatal(err) } if !o.IsSet() { t.Fatal("should be set") } if v, _ := o.Value(); v != 42 { t.Fatalf("got %d", v) } } func TestJsonOpt_StructWithJsonOpt(t *testing.T) { type S struct { A JsonOpt[int] `json:"a"` B JsonOpt[string] `json:"b"` } s := S{A: NewJsonOpt[int](1), B: EmptyJsonOpt[string]()} b, err := json.Marshal(s) if err != nil { t.Fatal(err) } if string(b) != `{"a":1,"b":null}` { t.Fatalf("got %s", b) } }