listor_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package internal
  2. import (
  3. "encoding/json"
  4. "testing"
  5. )
  6. func TestListOr_UnmarshalJSON(t *testing.T) {
  7. t.Run("single value should be unmarshaled as single item", func(t *testing.T) {
  8. var lo ListOr[string]
  9. err := json.Unmarshal([]byte(`"hello"`), &lo)
  10. if err != nil {
  11. t.Fatalf("Failed to unmarshal single string: %v", err)
  12. }
  13. if len(lo) != 1 {
  14. t.Fatalf("Expected 1 item, got %d", len(lo))
  15. }
  16. if lo[0] != "hello" {
  17. t.Errorf("Expected 'hello', got %q", lo[0])
  18. }
  19. })
  20. t.Run("array should be unmarshaled as multiple items", func(t *testing.T) {
  21. var lo ListOr[string]
  22. err := json.Unmarshal([]byte(`["hello", "world"]`), &lo)
  23. if err != nil {
  24. t.Fatalf("Failed to unmarshal array: %v", err)
  25. }
  26. if len(lo) != 2 {
  27. t.Fatalf("Expected 2 items, got %d", len(lo))
  28. }
  29. if lo[0] != "hello" {
  30. t.Errorf("Expected 'hello', got %q", lo[0])
  31. }
  32. if lo[1] != "world" {
  33. t.Errorf("Expected 'world', got %q", lo[1])
  34. }
  35. })
  36. t.Run("single number should be unmarshaled as single item", func(t *testing.T) {
  37. var lo ListOr[int]
  38. err := json.Unmarshal([]byte(`42`), &lo)
  39. if err != nil {
  40. t.Fatalf("Failed to unmarshal single number: %v", err)
  41. }
  42. if len(lo) != 1 {
  43. t.Fatalf("Expected 1 item, got %d", len(lo))
  44. }
  45. if lo[0] != 42 {
  46. t.Errorf("Expected 42, got %d", lo[0])
  47. }
  48. })
  49. t.Run("array of numbers should be unmarshaled as multiple items", func(t *testing.T) {
  50. var lo ListOr[int]
  51. err := json.Unmarshal([]byte(`[1, 2, 3]`), &lo)
  52. if err != nil {
  53. t.Fatalf("Failed to unmarshal number array: %v", err)
  54. }
  55. if len(lo) != 3 {
  56. t.Fatalf("Expected 3 items, got %d", len(lo))
  57. }
  58. if lo[0] != 1 || lo[1] != 2 || lo[2] != 3 {
  59. t.Errorf("Expected [1, 2, 3], got %v", lo)
  60. }
  61. })
  62. }