github.com/fluhus/gostuff@v0.4.1-0.20240331134726-be71864f2b5d/sets/sets_test.go (about) 1 package sets 2 3 import ( 4 "encoding/json" 5 "reflect" 6 "testing" 7 8 "golang.org/x/exp/maps" 9 ) 10 11 func TestJSON(t *testing.T) { 12 input := Set[int]{}.Add(1, 3, 6) 13 want := Set[int]{}.Add(1, 3, 6) 14 j, err := input.MarshalJSON() 15 if err != nil { 16 t.Fatalf("%v.MarshalJSON() failed: %v", input, err) 17 } 18 19 got := Set[int]{} 20 err = got.UnmarshalJSON(j) 21 if err != nil { 22 t.Fatalf("%v.UnmarshalJSON(%q) failed: %v", input, j, err) 23 } 24 25 if !maps.Equal(got, want) { 26 t.Fatalf("UnmarshalJSON(%q)=%v, want %v", j, got, want) 27 } 28 } 29 30 func TestJSON_slice(t *testing.T) { 31 input := []Set[int]{ 32 Set[int]{}.Add(1, 3, 6), 33 Set[int]{}.Add(7, 9, 6), 34 } 35 want := []Set[int]{ 36 Set[int]{}.Add(1, 3, 6), 37 Set[int]{}.Add(7, 9, 6), 38 } 39 j, err := json.Marshal(input) 40 if err != nil { 41 t.Fatalf("Marshal(%v) failed: %v", input, err) 42 } 43 44 got := []Set[int]{} 45 err = json.Unmarshal(j, &got) 46 if err != nil { 47 t.Fatalf("Unmarshal(%q) failed: %v", j, err) 48 } 49 50 if !reflect.DeepEqual(input, got) { 51 t.Fatalf("Unmarshal(%q)=%v, want %v", j, got, want) 52 } 53 } 54 55 func TestJSON_map(t *testing.T) { 56 input := map[string]Set[int]{ 57 "a": Set[int]{}.Add(1, 3, 6), 58 "x": Set[int]{}.Add(7, 9, 6), 59 } 60 want := map[string]Set[int]{ 61 "a": Set[int]{}.Add(1, 3, 6), 62 "x": Set[int]{}.Add(7, 9, 6), 63 } 64 j, err := json.Marshal(input) 65 if err != nil { 66 t.Fatalf("Marshal(%v) failed: %v", input, err) 67 } 68 69 got := map[string]Set[int]{} 70 err = json.Unmarshal(j, &got) 71 if err != nil { 72 t.Fatalf("Unmarshal(%q) failed: %v", j, err) 73 } 74 75 if !reflect.DeepEqual(input, got) { 76 t.Fatalf("Unmarshal(%q)=%v, want %v", j, got, want) 77 } 78 }