github.com/lingyao2333/mo-zero@v1.4.1/core/contextx/unmarshaler_test.go (about) 1 package contextx 2 3 import ( 4 "context" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func TestUnmarshalContext(t *testing.T) { 11 type Person struct { 12 Name string `ctx:"name"` 13 Age int `ctx:"age"` 14 } 15 16 ctx := context.Background() 17 ctx = context.WithValue(ctx, "name", "kevin") 18 ctx = context.WithValue(ctx, "age", 20) 19 20 var person Person 21 err := For(ctx, &person) 22 23 assert.Nil(t, err) 24 assert.Equal(t, "kevin", person.Name) 25 assert.Equal(t, 20, person.Age) 26 } 27 28 func TestUnmarshalContextWithOptional(t *testing.T) { 29 type Person struct { 30 Name string `ctx:"name"` 31 Age int `ctx:"age,optional"` 32 } 33 34 ctx := context.Background() 35 ctx = context.WithValue(ctx, "name", "kevin") 36 37 var person Person 38 err := For(ctx, &person) 39 40 assert.Nil(t, err) 41 assert.Equal(t, "kevin", person.Name) 42 assert.Equal(t, 0, person.Age) 43 } 44 45 func TestUnmarshalContextWithMissing(t *testing.T) { 46 type Person struct { 47 Name string `ctx:"name"` 48 Age int `ctx:"age"` 49 } 50 type name string 51 const PersonNameKey name = "name" 52 53 ctx := context.Background() 54 ctx = context.WithValue(ctx, PersonNameKey, "kevin") 55 56 var person Person 57 err := For(ctx, &person) 58 59 assert.NotNil(t, err) 60 }