prototest.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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 prototest exercises protobuf reflection.
  5. package prototest
  6. import (
  7. "bytes"
  8. "fmt"
  9. "math"
  10. "sort"
  11. "testing"
  12. "google.golang.org/protobuf/encoding/prototext"
  13. "google.golang.org/protobuf/internal/encoding/wire"
  14. "google.golang.org/protobuf/proto"
  15. pref "google.golang.org/protobuf/reflect/protoreflect"
  16. preg "google.golang.org/protobuf/reflect/protoregistry"
  17. )
  18. // TODO: Test read-only properties of unpopulated composite values.
  19. // TODO: Test invalid field descriptors or oneof descriptors.
  20. // TODO: This should test the functionality that can be provided by fast-paths.
  21. // MessageOptions configure message tests.
  22. type MessageOptions struct {
  23. // ExtensionTypes is a list of types to test with.
  24. //
  25. // If nil, TestMessage will look for extension types in the global registry.
  26. ExtensionTypes []pref.ExtensionType
  27. // Resolver is used for looking up types when unmarshaling extension fields.
  28. // If nil, this defaults to using protoregistry.GlobalTypes.
  29. Resolver interface {
  30. preg.ExtensionTypeResolver
  31. }
  32. }
  33. // TestMessage runs the provided m through a series of tests
  34. // exercising the protobuf reflection API.
  35. func TestMessage(t testing.TB, m proto.Message, opts MessageOptions) {
  36. md := m.ProtoReflect().Descriptor()
  37. m1 := m.ProtoReflect().New()
  38. for i := 0; i < md.Fields().Len(); i++ {
  39. fd := md.Fields().Get(i)
  40. testField(t, m1, fd)
  41. }
  42. if opts.ExtensionTypes == nil {
  43. preg.GlobalTypes.RangeExtensionsByMessage(md.FullName(), func(e pref.ExtensionType) bool {
  44. opts.ExtensionTypes = append(opts.ExtensionTypes, e)
  45. return true
  46. })
  47. }
  48. for _, xt := range opts.ExtensionTypes {
  49. testField(t, m1, xt.TypeDescriptor())
  50. }
  51. for i := 0; i < md.Oneofs().Len(); i++ {
  52. testOneof(t, m1, md.Oneofs().Get(i))
  53. }
  54. testUnknown(t, m1)
  55. // Test round-trip marshal/unmarshal.
  56. m2 := m.ProtoReflect().New().Interface()
  57. populateMessage(m2.ProtoReflect(), 1, nil)
  58. for _, xt := range opts.ExtensionTypes {
  59. m2.ProtoReflect().Set(xt.TypeDescriptor(), newValue(m2.ProtoReflect(), xt.TypeDescriptor(), 1, nil))
  60. }
  61. b, err := proto.MarshalOptions{
  62. AllowPartial: true,
  63. }.Marshal(m2)
  64. if err != nil {
  65. t.Errorf("Marshal() = %v, want nil\n%v", err, marshalText(m2))
  66. }
  67. m3 := m.ProtoReflect().New().Interface()
  68. if err := (proto.UnmarshalOptions{
  69. AllowPartial: true,
  70. Resolver: opts.Resolver,
  71. }.Unmarshal(b, m3)); err != nil {
  72. t.Errorf("Unmarshal() = %v, want nil\n%v", err, marshalText(m2))
  73. }
  74. if !proto.Equal(m2, m3) {
  75. t.Errorf("round-trip marshal/unmarshal did not preserve message\nOriginal:\n%v\nNew:\n%v", marshalText(m2), marshalText(m3))
  76. }
  77. }
  78. func marshalText(m proto.Message) string {
  79. b, _ := prototext.MarshalOptions{Indent: " "}.Marshal(m)
  80. return string(b)
  81. }
  82. // testField exercises set/get/has/clear of a field.
  83. func testField(t testing.TB, m pref.Message, fd pref.FieldDescriptor) {
  84. name := fd.FullName()
  85. num := fd.Number()
  86. switch {
  87. case fd.IsList():
  88. testFieldList(t, m, fd)
  89. case fd.IsMap():
  90. testFieldMap(t, m, fd)
  91. case fd.Message() != nil:
  92. default:
  93. if got, want := m.NewField(fd), fd.Default(); !valueEqual(got, want) {
  94. t.Errorf("Message.NewField(%v) = %v, want default value %v", name, formatValue(got), formatValue(want))
  95. }
  96. if fd.Kind() == pref.FloatKind || fd.Kind() == pref.DoubleKind {
  97. testFieldFloat(t, m, fd)
  98. }
  99. }
  100. // Set to a non-zero value, the zero value, different non-zero values.
  101. for _, n := range []seed{1, 0, minVal, maxVal} {
  102. v := newValue(m, fd, n, nil)
  103. m.Set(fd, v)
  104. wantHas := true
  105. if n == 0 {
  106. if fd.Syntax() == pref.Proto3 && fd.Message() == nil {
  107. wantHas = false
  108. }
  109. if fd.Cardinality() == pref.Repeated {
  110. wantHas = false
  111. }
  112. if fd.IsExtension() {
  113. wantHas = true
  114. }
  115. if fd.ContainingOneof() != nil {
  116. wantHas = true
  117. }
  118. }
  119. if fd.Syntax() == pref.Proto3 && fd.Cardinality() != pref.Repeated && fd.ContainingOneof() == nil && fd.Kind() == pref.EnumKind && v.Enum() == 0 {
  120. wantHas = false
  121. }
  122. if got, want := m.Has(fd), wantHas; got != want {
  123. t.Errorf("after setting %q to %v:\nMessage.Has(%v) = %v, want %v", name, formatValue(v), num, got, want)
  124. }
  125. if got, want := m.Get(fd), v; !valueEqual(got, want) {
  126. t.Errorf("after setting %q:\nMessage.Get(%v) = %v, want %v", name, num, formatValue(got), formatValue(want))
  127. }
  128. found := false
  129. m.Range(func(d pref.FieldDescriptor, got pref.Value) bool {
  130. if fd != d {
  131. return true
  132. }
  133. found = true
  134. if want := v; !valueEqual(got, want) {
  135. t.Errorf("after setting %q:\nMessage.Range got value %v, want %v", name, formatValue(got), formatValue(want))
  136. }
  137. return true
  138. })
  139. if got, want := wantHas, found; got != want {
  140. t.Errorf("after setting %q:\nMessageRange saw field: %v, want %v", name, got, want)
  141. }
  142. }
  143. m.Clear(fd)
  144. if got, want := m.Has(fd), false; got != want {
  145. t.Errorf("after clearing %q:\nMessage.Has(%v) = %v, want %v", name, num, got, want)
  146. }
  147. switch {
  148. case fd.IsList():
  149. if got := m.Get(fd); got.List().Len() != 0 {
  150. t.Errorf("after clearing %q:\nMessage.Get(%v) = %v, want empty list", name, num, formatValue(got))
  151. }
  152. case fd.IsMap():
  153. if got := m.Get(fd); got.Map().Len() != 0 {
  154. t.Errorf("after clearing %q:\nMessage.Get(%v) = %v, want empty map", name, num, formatValue(got))
  155. }
  156. case fd.Message() == nil:
  157. if got, want := m.Get(fd), fd.Default(); !valueEqual(got, want) {
  158. t.Errorf("after clearing %q:\nMessage.Get(%v) = %v, want default %v", name, num, formatValue(got), formatValue(want))
  159. }
  160. }
  161. // Set to the default value.
  162. switch {
  163. case fd.IsList() || fd.IsMap():
  164. m.Set(fd, m.Get(fd))
  165. if got, want := m.Has(fd), fd.IsExtension() || fd.ContainingOneof() != nil; got != want {
  166. t.Errorf("after setting %q to default:\nMessage.Has(%v) = %v, want %v", name, num, got, want)
  167. }
  168. case fd.Message() == nil:
  169. m.Set(fd, m.Get(fd))
  170. if got, want := m.Get(fd), fd.Default(); !valueEqual(got, want) {
  171. t.Errorf("after setting %q to default:\nMessage.Get(%v) = %v, want default %v", name, num, formatValue(got), formatValue(want))
  172. }
  173. }
  174. m.Clear(fd)
  175. // Set to the wrong type.
  176. v := pref.ValueOfString("")
  177. if fd.Kind() == pref.StringKind {
  178. v = pref.ValueOfInt32(0)
  179. }
  180. if !panics(func() {
  181. m.Set(fd, v)
  182. }) {
  183. t.Errorf("setting %v to %T succeeds, want panic", name, v.Interface())
  184. }
  185. }
  186. // testFieldMap tests set/get/has/clear of entries in a map field.
  187. func testFieldMap(t testing.TB, m pref.Message, fd pref.FieldDescriptor) {
  188. name := fd.FullName()
  189. num := fd.Number()
  190. // New values.
  191. m.Clear(fd) // start with an empty map
  192. mapv := m.Get(fd).Map()
  193. if got, want := mapv.NewValue(), newMapValue(fd, mapv, 0, nil); !valueEqual(got, want) {
  194. t.Errorf("message.Get(%v).NewValue() = %v, want %v", name, formatValue(got), formatValue(want))
  195. }
  196. mapv = m.Mutable(fd).Map() // mutable map
  197. if got, want := mapv.NewValue(), newMapValue(fd, mapv, 0, nil); !valueEqual(got, want) {
  198. t.Errorf("message.Mutable(%v).NewValue() = %v, want %v", name, formatValue(got), formatValue(want))
  199. }
  200. // Add values.
  201. want := make(testMap)
  202. for i, n := range []seed{1, 0, minVal, maxVal} {
  203. if got, want := m.Has(fd), i > 0; got != want {
  204. t.Errorf("after inserting %d elements to %q:\nMessage.Has(%v) = %v, want %v", i, name, num, got, want)
  205. }
  206. k := newMapKey(fd, n)
  207. v := newMapValue(fd, mapv, n, nil)
  208. mapv.Set(k, v)
  209. want.Set(k, v)
  210. if got, want := m.Get(fd), pref.ValueOfMap(want); !valueEqual(got, want) {
  211. t.Errorf("after inserting %d elements to %q:\nMessage.Get(%v) = %v, want %v", i, name, num, formatValue(got), formatValue(want))
  212. }
  213. }
  214. // Set values.
  215. want.Range(func(k pref.MapKey, v pref.Value) bool {
  216. nv := newMapValue(fd, mapv, 10, nil)
  217. mapv.Set(k, nv)
  218. want.Set(k, nv)
  219. if got, want := m.Get(fd), pref.ValueOfMap(want); !valueEqual(got, want) {
  220. t.Errorf("after setting element %v of %q:\nMessage.Get(%v) = %v, want %v", formatValue(k.Value()), name, num, formatValue(got), formatValue(want))
  221. }
  222. return true
  223. })
  224. // Clear values.
  225. want.Range(func(k pref.MapKey, v pref.Value) bool {
  226. mapv.Clear(k)
  227. want.Clear(k)
  228. if got, want := m.Has(fd), want.Len() > 0; got != want {
  229. t.Errorf("after clearing elements of %q:\nMessage.Has(%v) = %v, want %v", name, num, got, want)
  230. }
  231. if got, want := m.Get(fd), pref.ValueOfMap(want); !valueEqual(got, want) {
  232. t.Errorf("after clearing elements of %q:\nMessage.Get(%v) = %v, want %v", name, num, formatValue(got), formatValue(want))
  233. }
  234. return true
  235. })
  236. // Non-existent map keys.
  237. missingKey := newMapKey(fd, 1)
  238. if got, want := mapv.Has(missingKey), false; got != want {
  239. t.Errorf("non-existent map key in %q: Map.Has(%v) = %v, want %v", name, formatValue(missingKey.Value()), got, want)
  240. }
  241. if got, want := mapv.Get(missingKey).IsValid(), false; got != want {
  242. t.Errorf("non-existent map key in %q: Map.Get(%v).IsValid() = %v, want %v", name, formatValue(missingKey.Value()), got, want)
  243. }
  244. mapv.Clear(missingKey) // noop
  245. }
  246. type testMap map[interface{}]pref.Value
  247. func (m testMap) Get(k pref.MapKey) pref.Value { return m[k.Interface()] }
  248. func (m testMap) Set(k pref.MapKey, v pref.Value) { m[k.Interface()] = v }
  249. func (m testMap) Has(k pref.MapKey) bool { return m.Get(k).IsValid() }
  250. func (m testMap) Clear(k pref.MapKey) { delete(m, k.Interface()) }
  251. func (m testMap) Len() int { return len(m) }
  252. func (m testMap) NewValue() pref.Value { panic("unimplemented") }
  253. func (m testMap) Range(f func(pref.MapKey, pref.Value) bool) {
  254. for k, v := range m {
  255. if !f(pref.ValueOf(k).MapKey(), v) {
  256. return
  257. }
  258. }
  259. }
  260. // testFieldList exercises set/get/append/truncate of values in a list.
  261. func testFieldList(t testing.TB, m pref.Message, fd pref.FieldDescriptor) {
  262. name := fd.FullName()
  263. num := fd.Number()
  264. m.Clear(fd) // start with an empty list
  265. list := m.Get(fd).List()
  266. if got, want := list.NewElement(), newListElement(fd, list, 0, nil); !valueEqual(got, want) {
  267. t.Errorf("message.Get(%v).NewElement() = %v, want %v", name, formatValue(got), formatValue(want))
  268. }
  269. list = m.Mutable(fd).List() // mutable list
  270. if got, want := list.NewElement(), newListElement(fd, list, 0, nil); !valueEqual(got, want) {
  271. t.Errorf("message.Mutable(%v).NewElement() = %v, want %v", name, formatValue(got), formatValue(want))
  272. }
  273. // Append values.
  274. var want pref.List = &testList{}
  275. for i, n := range []seed{1, 0, minVal, maxVal} {
  276. if got, want := m.Has(fd), i > 0 || fd.IsExtension(); got != want {
  277. t.Errorf("after appending %d elements to %q:\nMessage.Has(%v) = %v, want %v", i, name, num, got, want)
  278. }
  279. v := newListElement(fd, list, n, nil)
  280. want.Append(v)
  281. list.Append(v)
  282. if got, want := m.Get(fd), pref.ValueOfList(want); !valueEqual(got, want) {
  283. t.Errorf("after appending %d elements to %q:\nMessage.Get(%v) = %v, want %v", i+1, name, num, formatValue(got), formatValue(want))
  284. }
  285. }
  286. // Set values.
  287. for i := 0; i < want.Len(); i++ {
  288. v := newListElement(fd, list, seed(i+10), nil)
  289. want.Set(i, v)
  290. list.Set(i, v)
  291. if got, want := m.Get(fd), pref.ValueOfList(want); !valueEqual(got, want) {
  292. t.Errorf("after setting element %d of %q:\nMessage.Get(%v) = %v, want %v", i, name, num, formatValue(got), formatValue(want))
  293. }
  294. }
  295. // Truncate.
  296. for want.Len() > 0 {
  297. n := want.Len() - 1
  298. want.Truncate(n)
  299. list.Truncate(n)
  300. if got, want := m.Has(fd), want.Len() > 0 || fd.IsExtension(); got != want {
  301. t.Errorf("after truncating %q to %d:\nMessage.Has(%v) = %v, want %v", name, n, num, got, want)
  302. }
  303. if got, want := m.Get(fd), pref.ValueOfList(want); !valueEqual(got, want) {
  304. t.Errorf("after truncating %q to %d:\nMessage.Get(%v) = %v, want %v", name, n, num, formatValue(got), formatValue(want))
  305. }
  306. }
  307. }
  308. type testList struct {
  309. a []pref.Value
  310. }
  311. func (l *testList) Append(v pref.Value) { l.a = append(l.a, v) }
  312. func (l *testList) Get(n int) pref.Value { return l.a[n] }
  313. func (l *testList) Len() int { return len(l.a) }
  314. func (l *testList) Set(n int, v pref.Value) { l.a[n] = v }
  315. func (l *testList) Truncate(n int) { l.a = l.a[:n] }
  316. func (l *testList) NewElement() pref.Value { panic("unimplemented") }
  317. // testFieldFloat exercises some interesting floating-point scalar field values.
  318. func testFieldFloat(t testing.TB, m pref.Message, fd pref.FieldDescriptor) {
  319. name := fd.FullName()
  320. num := fd.Number()
  321. for _, v := range []float64{math.Inf(-1), math.Inf(1), math.NaN(), math.Copysign(0, -1)} {
  322. var val pref.Value
  323. if fd.Kind() == pref.FloatKind {
  324. val = pref.ValueOfFloat32(float32(v))
  325. } else {
  326. val = pref.ValueOfFloat64(float64(v))
  327. }
  328. m.Set(fd, val)
  329. // Note that Has is true for -0.
  330. if got, want := m.Has(fd), true; got != want {
  331. t.Errorf("after setting %v to %v: Message.Has(%v) = %v, want %v", name, v, num, got, want)
  332. }
  333. if got, want := m.Get(fd), val; !valueEqual(got, want) {
  334. t.Errorf("after setting %v: Message.Get(%v) = %v, want %v", name, num, formatValue(got), formatValue(want))
  335. }
  336. }
  337. }
  338. // testOneof tests the behavior of fields in a oneof.
  339. func testOneof(t testing.TB, m pref.Message, od pref.OneofDescriptor) {
  340. for _, mutable := range []bool{false, true} {
  341. for i := 0; i < od.Fields().Len(); i++ {
  342. fda := od.Fields().Get(i)
  343. if mutable {
  344. // Set fields by requesting a mutable reference.
  345. if !fda.IsMap() && !fda.IsList() && fda.Message() == nil {
  346. continue
  347. }
  348. _ = m.Mutable(fda)
  349. } else {
  350. // Set fields explicitly.
  351. m.Set(fda, newValue(m, fda, 1, nil))
  352. }
  353. if got, want := m.WhichOneof(od), fda; got != want {
  354. t.Errorf("after setting oneof field %q:\nWhichOneof(%q) = %v, want %v", fda.FullName(), fda.Name(), got, want)
  355. }
  356. for j := 0; j < od.Fields().Len(); j++ {
  357. fdb := od.Fields().Get(j)
  358. if got, want := m.Has(fdb), i == j; got != want {
  359. t.Errorf("after setting oneof field %q:\nGet(%q) = %v, want %v", fda.FullName(), fdb.FullName(), got, want)
  360. }
  361. }
  362. }
  363. }
  364. }
  365. // testUnknown tests the behavior of unknown fields.
  366. func testUnknown(t testing.TB, m pref.Message) {
  367. var b []byte
  368. b = wire.AppendTag(b, 1000, wire.VarintType)
  369. b = wire.AppendVarint(b, 1001)
  370. m.SetUnknown(pref.RawFields(b))
  371. if got, want := []byte(m.GetUnknown()), b; !bytes.Equal(got, want) {
  372. t.Errorf("after setting unknown fields:\nGetUnknown() = %v, want %v", got, want)
  373. }
  374. }
  375. func formatValue(v pref.Value) string {
  376. switch v := v.Interface().(type) {
  377. case pref.List:
  378. var buf bytes.Buffer
  379. buf.WriteString("list[")
  380. for i := 0; i < v.Len(); i++ {
  381. if i > 0 {
  382. buf.WriteString(" ")
  383. }
  384. buf.WriteString(formatValue(v.Get(i)))
  385. }
  386. buf.WriteString("]")
  387. return buf.String()
  388. case pref.Map:
  389. var buf bytes.Buffer
  390. buf.WriteString("map[")
  391. var keys []pref.MapKey
  392. v.Range(func(k pref.MapKey, v pref.Value) bool {
  393. keys = append(keys, k)
  394. return true
  395. })
  396. sort.Slice(keys, func(i, j int) bool {
  397. return keys[i].String() < keys[j].String()
  398. })
  399. for i, k := range keys {
  400. if i > 0 {
  401. buf.WriteString(" ")
  402. }
  403. buf.WriteString(formatValue(k.Value()))
  404. buf.WriteString(":")
  405. buf.WriteString(formatValue(v.Get(k)))
  406. }
  407. buf.WriteString("]")
  408. return buf.String()
  409. case pref.Message:
  410. b, err := prototext.Marshal(v.Interface())
  411. if err != nil {
  412. return fmt.Sprintf("<%v>", err)
  413. }
  414. return fmt.Sprintf("%v{%v}", v.Descriptor().FullName(), string(b))
  415. case string:
  416. return fmt.Sprintf("%q", v)
  417. default:
  418. return fmt.Sprint(v)
  419. }
  420. }
  421. func valueEqual(a, b pref.Value) bool {
  422. ai, bi := a.Interface(), b.Interface()
  423. switch ai.(type) {
  424. case pref.Message:
  425. return proto.Equal(
  426. a.Message().Interface(),
  427. b.Message().Interface(),
  428. )
  429. case pref.List:
  430. lista, listb := a.List(), b.List()
  431. if lista.Len() != listb.Len() {
  432. return false
  433. }
  434. for i := 0; i < lista.Len(); i++ {
  435. if !valueEqual(lista.Get(i), listb.Get(i)) {
  436. return false
  437. }
  438. }
  439. return true
  440. case pref.Map:
  441. mapa, mapb := a.Map(), b.Map()
  442. if mapa.Len() != mapb.Len() {
  443. return false
  444. }
  445. equal := true
  446. mapa.Range(func(k pref.MapKey, v pref.Value) bool {
  447. if !valueEqual(v, mapb.Get(k)) {
  448. equal = false
  449. return false
  450. }
  451. return true
  452. })
  453. return equal
  454. case []byte:
  455. return bytes.Equal(a.Bytes(), b.Bytes())
  456. case float32:
  457. // NaNs are equal, but must be the same NaN.
  458. return math.Float32bits(ai.(float32)) == math.Float32bits(bi.(float32))
  459. case float64:
  460. // NaNs are equal, but must be the same NaN.
  461. return math.Float64bits(ai.(float64)) == math.Float64bits(bi.(float64))
  462. default:
  463. return ai == bi
  464. }
  465. }
  466. // A seed is used to vary the content of a value.
  467. //
  468. // A seed of 0 is the zero value. Messages do not have a zero-value; a 0-seeded messages
  469. // is unpopulated.
  470. //
  471. // A seed of minVal or maxVal is the least or greatest value of the value type.
  472. type seed int
  473. const (
  474. minVal seed = -1
  475. maxVal seed = -2
  476. )
  477. // newSeed creates new seed values from a base, for example to create seeds for the
  478. // elements in a list. If the input seed is minVal or maxVal, so is the output.
  479. func newSeed(n seed, adjust ...int) seed {
  480. switch n {
  481. case minVal, maxVal:
  482. return n
  483. }
  484. for _, a := range adjust {
  485. n = 10*n + seed(a)
  486. }
  487. return n
  488. }
  489. // newValue returns a new value assignable to a field.
  490. //
  491. // The stack parameter is used to avoid infinite recursion when populating circular
  492. // data structures.
  493. func newValue(m pref.Message, fd pref.FieldDescriptor, n seed, stack []pref.MessageDescriptor) pref.Value {
  494. switch {
  495. case fd.IsList():
  496. if n == 0 {
  497. return m.New().Get(fd)
  498. }
  499. list := m.NewField(fd).List()
  500. list.Append(newListElement(fd, list, 0, stack))
  501. list.Append(newListElement(fd, list, minVal, stack))
  502. list.Append(newListElement(fd, list, maxVal, stack))
  503. list.Append(newListElement(fd, list, n, stack))
  504. return pref.ValueOfList(list)
  505. case fd.IsMap():
  506. if n == 0 {
  507. return m.New().Get(fd)
  508. }
  509. mapv := m.NewField(fd).Map()
  510. mapv.Set(newMapKey(fd, 0), newMapValue(fd, mapv, 0, stack))
  511. mapv.Set(newMapKey(fd, minVal), newMapValue(fd, mapv, minVal, stack))
  512. mapv.Set(newMapKey(fd, maxVal), newMapValue(fd, mapv, maxVal, stack))
  513. mapv.Set(newMapKey(fd, n), newMapValue(fd, mapv, newSeed(n, 0), stack))
  514. return pref.ValueOfMap(mapv)
  515. case fd.Message() != nil:
  516. //if n == 0 {
  517. // return m.New().Get(fd)
  518. //}
  519. return populateMessage(m.NewField(fd).Message(), n, stack)
  520. default:
  521. return newScalarValue(fd, n)
  522. }
  523. }
  524. func newListElement(fd pref.FieldDescriptor, list pref.List, n seed, stack []pref.MessageDescriptor) pref.Value {
  525. if fd.Message() == nil {
  526. return newScalarValue(fd, n)
  527. }
  528. return populateMessage(list.NewElement().Message(), n, stack)
  529. }
  530. func newMapKey(fd pref.FieldDescriptor, n seed) pref.MapKey {
  531. kd := fd.MapKey()
  532. return newScalarValue(kd, n).MapKey()
  533. }
  534. func newMapValue(fd pref.FieldDescriptor, mapv pref.Map, n seed, stack []pref.MessageDescriptor) pref.Value {
  535. vd := fd.MapValue()
  536. if vd.Message() == nil {
  537. return newScalarValue(vd, n)
  538. }
  539. return populateMessage(mapv.NewValue().Message(), n, stack)
  540. }
  541. func newScalarValue(fd pref.FieldDescriptor, n seed) pref.Value {
  542. switch fd.Kind() {
  543. case pref.BoolKind:
  544. return pref.ValueOfBool(n != 0)
  545. case pref.EnumKind:
  546. vals := fd.Enum().Values()
  547. var i int
  548. switch n {
  549. case minVal:
  550. i = 0
  551. case maxVal:
  552. i = vals.Len() - 1
  553. default:
  554. i = int(n) % vals.Len()
  555. }
  556. return pref.ValueOfEnum(vals.Get(i).Number())
  557. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  558. switch n {
  559. case minVal:
  560. return pref.ValueOfInt32(math.MinInt32)
  561. case maxVal:
  562. return pref.ValueOfInt32(math.MaxInt32)
  563. default:
  564. return pref.ValueOfInt32(int32(n))
  565. }
  566. case pref.Uint32Kind, pref.Fixed32Kind:
  567. switch n {
  568. case minVal:
  569. // Only use 0 for the zero value.
  570. return pref.ValueOfUint32(1)
  571. case maxVal:
  572. return pref.ValueOfUint32(math.MaxInt32)
  573. default:
  574. return pref.ValueOfUint32(uint32(n))
  575. }
  576. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  577. switch n {
  578. case minVal:
  579. return pref.ValueOfInt64(math.MinInt64)
  580. case maxVal:
  581. return pref.ValueOfInt64(math.MaxInt64)
  582. default:
  583. return pref.ValueOfInt64(int64(n))
  584. }
  585. case pref.Uint64Kind, pref.Fixed64Kind:
  586. switch n {
  587. case minVal:
  588. // Only use 0 for the zero value.
  589. return pref.ValueOfUint64(1)
  590. case maxVal:
  591. return pref.ValueOfUint64(math.MaxInt64)
  592. default:
  593. return pref.ValueOfUint64(uint64(n))
  594. }
  595. case pref.FloatKind:
  596. switch n {
  597. case minVal:
  598. return pref.ValueOfFloat32(math.SmallestNonzeroFloat32)
  599. case maxVal:
  600. return pref.ValueOfFloat32(math.MaxFloat32)
  601. default:
  602. return pref.ValueOfFloat32(1.5 * float32(n))
  603. }
  604. case pref.DoubleKind:
  605. switch n {
  606. case minVal:
  607. return pref.ValueOfFloat64(math.SmallestNonzeroFloat64)
  608. case maxVal:
  609. return pref.ValueOfFloat64(math.MaxFloat64)
  610. default:
  611. return pref.ValueOfFloat64(1.5 * float64(n))
  612. }
  613. case pref.StringKind:
  614. if n == 0 {
  615. return pref.ValueOfString("")
  616. }
  617. return pref.ValueOfString(fmt.Sprintf("%d", n))
  618. case pref.BytesKind:
  619. if n == 0 {
  620. return pref.ValueOfBytes(nil)
  621. }
  622. return pref.ValueOfBytes([]byte{byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)})
  623. }
  624. panic("unhandled kind")
  625. }
  626. func populateMessage(m pref.Message, n seed, stack []pref.MessageDescriptor) pref.Value {
  627. if n == 0 {
  628. return pref.ValueOfMessage(m)
  629. }
  630. md := m.Descriptor()
  631. for _, x := range stack {
  632. if md == x {
  633. return pref.ValueOfMessage(m)
  634. }
  635. }
  636. stack = append(stack, md)
  637. for i := 0; i < md.Fields().Len(); i++ {
  638. fd := md.Fields().Get(i)
  639. if fd.IsWeak() {
  640. continue
  641. }
  642. m.Set(fd, newValue(m, fd, newSeed(n, i), stack))
  643. }
  644. return pref.ValueOfMessage(m)
  645. }
  646. func panics(f func()) (didPanic bool) {
  647. defer func() {
  648. if err := recover(); err != nil {
  649. didPanic = true
  650. }
  651. }()
  652. f()
  653. return false
  654. }