unmarshaler_test.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package contextx
  2. import (
  3. "context"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestUnmarshalContext(t *testing.T) {
  8. type Person struct {
  9. Name string `ctx:"name"`
  10. Age int `ctx:"age"`
  11. }
  12. ctx := context.Background()
  13. ctx = context.WithValue(ctx, "name", "kevin")
  14. ctx = context.WithValue(ctx, "age", 20)
  15. var person Person
  16. err := For(ctx, &person)
  17. assert.Nil(t, err)
  18. assert.Equal(t, "kevin", person.Name)
  19. assert.Equal(t, 20, person.Age)
  20. }
  21. func TestUnmarshalContextWithOptional(t *testing.T) {
  22. type Person struct {
  23. Name string `ctx:"name"`
  24. Age int `ctx:"age,optional"`
  25. }
  26. ctx := context.Background()
  27. ctx = context.WithValue(ctx, "name", "kevin")
  28. var person Person
  29. err := For(ctx, &person)
  30. assert.Nil(t, err)
  31. assert.Equal(t, "kevin", person.Name)
  32. assert.Equal(t, 0, person.Age)
  33. }
  34. func TestUnmarshalContextWithMissing(t *testing.T) {
  35. type Person struct {
  36. Name string `ctx:"name"`
  37. Age int `ctx:"age"`
  38. }
  39. ctx := context.Background()
  40. ctx = context.WithValue(ctx, "name", "kevin")
  41. var person Person
  42. err := For(ctx, &person)
  43. assert.NotNil(t, err)
  44. }