mapsort_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2019 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package mapsort_test
  5. import (
  6. "strconv"
  7. "testing"
  8. "google.golang.org/protobuf/internal/mapsort"
  9. testpb "google.golang.org/protobuf/internal/testprotos/test"
  10. pref "google.golang.org/protobuf/reflect/protoreflect"
  11. )
  12. func TestRange(t *testing.T) {
  13. m := (&testpb.TestAllTypes{
  14. MapBoolBool: map[bool]bool{
  15. false: false,
  16. true: true,
  17. },
  18. MapInt32Int32: map[int32]int32{
  19. 0: 0,
  20. 1: 1,
  21. 2: 2,
  22. },
  23. MapUint64Uint64: map[uint64]uint64{
  24. 0: 0,
  25. 1: 1,
  26. 2: 2,
  27. },
  28. MapStringString: map[string]string{
  29. "0": "0",
  30. "1": "1",
  31. "2": "2",
  32. },
  33. }).ProtoReflect()
  34. m.Range(func(fd pref.FieldDescriptor, v pref.Value) bool {
  35. mapv := v.Map()
  36. var got []pref.MapKey
  37. mapsort.Range(mapv, fd.MapKey().Kind(), func(key pref.MapKey, _ pref.Value) bool {
  38. got = append(got, key)
  39. return true
  40. })
  41. for wanti, key := range got {
  42. var goti int
  43. switch x := mapv.Get(key).Interface().(type) {
  44. case bool:
  45. if x {
  46. goti = 1
  47. }
  48. case int32:
  49. goti = int(x)
  50. case uint64:
  51. goti = int(x)
  52. case string:
  53. goti, _ = strconv.Atoi(x)
  54. default:
  55. t.Fatalf("unhandled map value type %T", x)
  56. }
  57. if wanti != goti {
  58. t.Errorf("out of order range over map field %v: %v", fd.FullName(), got)
  59. break
  60. }
  61. }
  62. return true
  63. })
  64. }