| 1 |
package encoder |
| 2 |
|
| 3 |
import ( |
| 4 |
"reflect" |
| 5 |
"testing" |
| 6 |
"time" |
| 7 |
) |
| 8 |
|
| 9 |
type embeddedTime struct{ time.Time } |
| 10 |
|
| 11 |
type embeddedTimePointer struct{ *time.Time } |
| 12 |
|
| 13 |
type declaredTime struct{ time.Time } |
| 14 |
|
| 15 |
func (declaredTime) MarshalJSON() ([]byte, error) { return []byte(`"t"`), nil } |
| 16 |
|
| 17 |
// A type which has the MarshalJSON of time.Time only by embedding it is trusted, and written from the embedded |
| 18 |
// value by AppendText when the value is in it; a type which declares the method is checked. |
| 19 |
func TestEmbeddedStdMarshalerCall(t *testing.T) { |
| 20 |
tests := []struct { |
| 21 |
typ reflect.Type |
| 22 |
trusted bool |
| 23 |
appendOutput bool |
| 24 |
}{ |
| 25 |
{reflect.TypeOf(embeddedTime{}), true, true}, |
| 26 |
{reflect.TypeOf(&embeddedTime{}), true, true}, |
| 27 |
{reflect.TypeOf(embeddedTimePointer{}), true, false}, |
| 28 |
{reflect.TypeOf(declaredTime{}), false, false}, |
| 29 |
} |
| 30 |
// AppendText is of Go 1.24: time.Time.MarshalJSON is called before it. |
| 31 |
hasAppendText := stdJSONAppender(reflect.TypeOf(time.Time{})) != nil |
| 32 |
for _, test := range tests { |
| 33 |
m := newMarshalerCall(test.typ, marshalJSONInterface) |
| 34 |
if m == nil || m.trusted != test.trusted || (m.appendOutput != nil) != (test.appendOutput && hasAppendText) { |
| 35 |
t.Errorf("%v: got %+v, want trusted %v and appendOutput %v", test.typ, m, test.trusted, test.appendOutput) |
| 36 |
} |
| 37 |
} |
| 38 |
text := newMarshalerCall(reflect.TypeOf(embeddedTime{}), marshalTextInterface) |
| 39 |
if text == nil || (text.appendOutput != nil) != hasAppendText { |
| 40 |
t.Fatal("the text of an embedded time.Time is not appended by AppendText") |
| 41 |
} |
| 42 |
} |