prototest.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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.ValueOf("")
  177. if fd.Kind() == pref.StringKind {
  178. v = pref.ValueOf(int32(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.ValueOf(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.ValueOf(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.ValueOf(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) NewMessage() pref.Message { panic("unimplemented") }
  253. func (m testMap) NewValue() pref.Value { panic("unimplemented") }
  254. func (m testMap) Range(f func(pref.MapKey, pref.Value) bool) {
  255. for k, v := range m {
  256. if !f(pref.ValueOf(k).MapKey(), v) {
  257. return
  258. }
  259. }
  260. }
  261. // testFieldList exercises set/get/append/truncate of values in a list.
  262. func testFieldList(t testing.TB, m pref.Message, fd pref.FieldDescriptor) {
  263. name := fd.FullName()
  264. num := fd.Number()
  265. m.Clear(fd) // start with an empty list
  266. list := m.Get(fd).List()
  267. if got, want := list.NewElement(), newListElement(fd, list, 0, nil); !valueEqual(got, want) {
  268. t.Errorf("message.Get(%v).NewElement() = %v, want %v", name, formatValue(got), formatValue(want))
  269. }
  270. list = m.Mutable(fd).List() // mutable list
  271. if got, want := list.NewElement(), newListElement(fd, list, 0, nil); !valueEqual(got, want) {
  272. t.Errorf("message.Mutable(%v).NewElement() = %v, want %v", name, formatValue(got), formatValue(want))
  273. }
  274. // Append values.
  275. var want pref.List = &testList{}
  276. for i, n := range []seed{1, 0, minVal, maxVal} {
  277. if got, want := m.Has(fd), i > 0 || fd.IsExtension(); got != want {
  278. t.Errorf("after appending %d elements to %q:\nMessage.Has(%v) = %v, want %v", i, name, num, got, want)
  279. }
  280. v := newListElement(fd, list, n, nil)
  281. want.Append(v)
  282. list.Append(v)
  283. if got, want := m.Get(fd), pref.ValueOf(want); !valueEqual(got, want) {
  284. t.Errorf("after appending %d elements to %q:\nMessage.Get(%v) = %v, want %v", i+1, name, num, formatValue(got), formatValue(want))
  285. }
  286. }
  287. // Set values.
  288. for i := 0; i < want.Len(); i++ {
  289. v := newListElement(fd, list, seed(i+10), nil)
  290. want.Set(i, v)
  291. list.Set(i, v)
  292. if got, want := m.Get(fd), pref.ValueOf(want); !valueEqual(got, want) {
  293. t.Errorf("after setting element %d of %q:\nMessage.Get(%v) = %v, want %v", i, name, num, formatValue(got), formatValue(want))
  294. }
  295. }
  296. // Truncate.
  297. for want.Len() > 0 {
  298. n := want.Len() - 1
  299. want.Truncate(n)
  300. list.Truncate(n)
  301. if got, want := m.Has(fd), want.Len() > 0 || fd.IsExtension(); got != want {
  302. t.Errorf("after truncating %q to %d:\nMessage.Has(%v) = %v, want %v", name, n, num, got, want)
  303. }
  304. if got, want := m.Get(fd), pref.ValueOf(want); !valueEqual(got, want) {
  305. t.Errorf("after truncating %q to %d:\nMessage.Get(%v) = %v, want %v", name, n, num, formatValue(got), formatValue(want))
  306. }
  307. }
  308. }
  309. type testList struct {
  310. a []pref.Value
  311. }
  312. func (l *testList) Append(v pref.Value) { l.a = append(l.a, v) }
  313. func (l *testList) Get(n int) pref.Value { return l.a[n] }
  314. func (l *testList) Len() int { return len(l.a) }
  315. func (l *testList) Set(n int, v pref.Value) { l.a[n] = v }
  316. func (l *testList) Truncate(n int) { l.a = l.a[:n] }
  317. func (l *testList) NewMessage() pref.Message { panic("unimplemented") }
  318. func (l *testList) NewElement() pref.Value { panic("unimplemented") }
  319. // testFieldFloat exercises some interesting floating-point scalar field values.
  320. func testFieldFloat(t testing.TB, m pref.Message, fd pref.FieldDescriptor) {
  321. name := fd.FullName()
  322. num := fd.Number()
  323. for _, v := range []float64{math.Inf(-1), math.Inf(1), math.NaN(), math.Copysign(0, -1)} {
  324. var val pref.Value
  325. if fd.Kind() == pref.FloatKind {
  326. val = pref.ValueOf(float32(v))
  327. } else {
  328. val = pref.ValueOf(v)
  329. }
  330. m.Set(fd, val)
  331. // Note that Has is true for -0.
  332. if got, want := m.Has(fd), true; got != want {
  333. t.Errorf("after setting %v to %v: Message.Has(%v) = %v, want %v", name, v, num, got, want)
  334. }
  335. if got, want := m.Get(fd), val; !valueEqual(got, want) {
  336. t.Errorf("after setting %v: Message.Get(%v) = %v, want %v", name, num, formatValue(got), formatValue(want))
  337. }
  338. }
  339. }
  340. // testOneof tests the behavior of fields in a oneof.
  341. func testOneof(t testing.TB, m pref.Message, od pref.OneofDescriptor) {
  342. for _, mutable := range []bool{false, true} {
  343. for i := 0; i < od.Fields().Len(); i++ {
  344. fda := od.Fields().Get(i)
  345. if mutable {
  346. // Set fields by requesting a mutable reference.
  347. if !fda.IsMap() && !fda.IsList() && fda.Message() == nil {
  348. continue
  349. }
  350. _ = m.Mutable(fda)
  351. } else {
  352. // Set fields explicitly.
  353. m.Set(fda, newValue(m, fda, 1, nil))
  354. }
  355. if got, want := m.WhichOneof(od), fda; got != want {
  356. t.Errorf("after setting oneof field %q:\nWhichOneof(%q) = %v, want %v", fda.FullName(), fda.Name(), got, want)
  357. }
  358. for j := 0; j < od.Fields().Len(); j++ {
  359. fdb := od.Fields().Get(j)
  360. if got, want := m.Has(fdb), i == j; got != want {
  361. t.Errorf("after setting oneof field %q:\nGet(%q) = %v, want %v", fda.FullName(), fdb.FullName(), got, want)
  362. }
  363. }
  364. }
  365. }
  366. }
  367. // testUnknown tests the behavior of unknown fields.
  368. func testUnknown(t testing.TB, m pref.Message) {
  369. var b []byte
  370. b = wire.AppendTag(b, 1000, wire.VarintType)
  371. b = wire.AppendVarint(b, 1001)
  372. m.SetUnknown(pref.RawFields(b))
  373. if got, want := []byte(m.GetUnknown()), b; !bytes.Equal(got, want) {
  374. t.Errorf("after setting unknown fields:\nGetUnknown() = %v, want %v", got, want)
  375. }
  376. }
  377. func formatValue(v pref.Value) string {
  378. switch v := v.Interface().(type) {
  379. case pref.List:
  380. var buf bytes.Buffer
  381. buf.WriteString("list[")
  382. for i := 0; i < v.Len(); i++ {
  383. if i > 0 {
  384. buf.WriteString(" ")
  385. }
  386. buf.WriteString(formatValue(v.Get(i)))
  387. }
  388. buf.WriteString("]")
  389. return buf.String()
  390. case pref.Map:
  391. var buf bytes.Buffer
  392. buf.WriteString("map[")
  393. var keys []pref.MapKey
  394. v.Range(func(k pref.MapKey, v pref.Value) bool {
  395. keys = append(keys, k)
  396. return true
  397. })
  398. sort.Slice(keys, func(i, j int) bool {
  399. return keys[i].String() < keys[j].String()
  400. })
  401. for i, k := range keys {
  402. if i > 0 {
  403. buf.WriteString(" ")
  404. }
  405. buf.WriteString(formatValue(k.Value()))
  406. buf.WriteString(":")
  407. buf.WriteString(formatValue(v.Get(k)))
  408. }
  409. buf.WriteString("]")
  410. return buf.String()
  411. case pref.Message:
  412. b, err := prototext.Marshal(v.Interface())
  413. if err != nil {
  414. return fmt.Sprintf("<%v>", err)
  415. }
  416. return fmt.Sprintf("%v{%v}", v.Descriptor().FullName(), string(b))
  417. case string:
  418. return fmt.Sprintf("%q", v)
  419. default:
  420. return fmt.Sprint(v)
  421. }
  422. }
  423. func valueEqual(a, b pref.Value) bool {
  424. ai, bi := a.Interface(), b.Interface()
  425. switch ai.(type) {
  426. case pref.Message:
  427. return proto.Equal(
  428. a.Message().Interface(),
  429. b.Message().Interface(),
  430. )
  431. case pref.List:
  432. lista, listb := a.List(), b.List()
  433. if lista.Len() != listb.Len() {
  434. return false
  435. }
  436. for i := 0; i < lista.Len(); i++ {
  437. if !valueEqual(lista.Get(i), listb.Get(i)) {
  438. return false
  439. }
  440. }
  441. return true
  442. case pref.Map:
  443. mapa, mapb := a.Map(), b.Map()
  444. if mapa.Len() != mapb.Len() {
  445. return false
  446. }
  447. equal := true
  448. mapa.Range(func(k pref.MapKey, v pref.Value) bool {
  449. if !valueEqual(v, mapb.Get(k)) {
  450. equal = false
  451. return false
  452. }
  453. return true
  454. })
  455. return equal
  456. case []byte:
  457. return bytes.Equal(a.Bytes(), b.Bytes())
  458. case float32:
  459. // NaNs are equal, but must be the same NaN.
  460. return math.Float32bits(ai.(float32)) == math.Float32bits(bi.(float32))
  461. case float64:
  462. // NaNs are equal, but must be the same NaN.
  463. return math.Float64bits(ai.(float64)) == math.Float64bits(bi.(float64))
  464. default:
  465. return ai == bi
  466. }
  467. }
  468. // A seed is used to vary the content of a value.
  469. //
  470. // A seed of 0 is the zero value. Messages do not have a zero-value; a 0-seeded messages
  471. // is unpopulated.
  472. //
  473. // A seed of minVal or maxVal is the least or greatest value of the value type.
  474. type seed int
  475. const (
  476. minVal seed = -1
  477. maxVal seed = -2
  478. )
  479. // newSeed creates new seed values from a base, for example to create seeds for the
  480. // elements in a list. If the input seed is minVal or maxVal, so is the output.
  481. func newSeed(n seed, adjust ...int) seed {
  482. switch n {
  483. case minVal, maxVal:
  484. return n
  485. }
  486. for _, a := range adjust {
  487. n = 10*n + seed(a)
  488. }
  489. return n
  490. }
  491. // newValue returns a new value assignable to a field.
  492. //
  493. // The stack parameter is used to avoid infinite recursion when populating circular
  494. // data structures.
  495. func newValue(m pref.Message, fd pref.FieldDescriptor, n seed, stack []pref.MessageDescriptor) pref.Value {
  496. switch {
  497. case fd.IsList():
  498. if n == 0 {
  499. return m.New().Get(fd)
  500. }
  501. list := m.NewField(fd).List()
  502. list.Append(newListElement(fd, list, 0, stack))
  503. list.Append(newListElement(fd, list, minVal, stack))
  504. list.Append(newListElement(fd, list, maxVal, stack))
  505. list.Append(newListElement(fd, list, n, stack))
  506. return pref.ValueOf(list)
  507. case fd.IsMap():
  508. if n == 0 {
  509. return m.New().Get(fd)
  510. }
  511. mapv := m.NewField(fd).Map()
  512. mapv.Set(newMapKey(fd, 0), newMapValue(fd, mapv, 0, stack))
  513. mapv.Set(newMapKey(fd, minVal), newMapValue(fd, mapv, minVal, stack))
  514. mapv.Set(newMapKey(fd, maxVal), newMapValue(fd, mapv, maxVal, stack))
  515. mapv.Set(newMapKey(fd, n), newMapValue(fd, mapv, newSeed(n, 0), stack))
  516. return pref.ValueOf(mapv)
  517. case fd.Message() != nil:
  518. //if n == 0 {
  519. // return m.New().Get(fd)
  520. //}
  521. return populateMessage(m.NewField(fd).Message(), n, stack)
  522. default:
  523. return newScalarValue(fd, n)
  524. }
  525. }
  526. func newListElement(fd pref.FieldDescriptor, list pref.List, n seed, stack []pref.MessageDescriptor) pref.Value {
  527. if fd.Message() == nil {
  528. return newScalarValue(fd, n)
  529. }
  530. return populateMessage(list.NewElement().Message(), n, stack)
  531. }
  532. func newMapKey(fd pref.FieldDescriptor, n seed) pref.MapKey {
  533. kd := fd.MapKey()
  534. return newScalarValue(kd, n).MapKey()
  535. }
  536. func newMapValue(fd pref.FieldDescriptor, mapv pref.Map, n seed, stack []pref.MessageDescriptor) pref.Value {
  537. vd := fd.MapValue()
  538. if vd.Message() == nil {
  539. return newScalarValue(vd, n)
  540. }
  541. return populateMessage(mapv.NewValue().Message(), n, stack)
  542. }
  543. func newScalarValue(fd pref.FieldDescriptor, n seed) pref.Value {
  544. switch fd.Kind() {
  545. case pref.BoolKind:
  546. return pref.ValueOf(n != 0)
  547. case pref.EnumKind:
  548. vals := fd.Enum().Values()
  549. var i int
  550. switch n {
  551. case minVal:
  552. i = 0
  553. case maxVal:
  554. i = vals.Len() - 1
  555. default:
  556. i = int(n) % vals.Len()
  557. }
  558. return pref.ValueOf(vals.Get(i).Number())
  559. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  560. switch n {
  561. case minVal:
  562. return pref.ValueOf(int32(math.MinInt32))
  563. case maxVal:
  564. return pref.ValueOf(int32(math.MaxInt32))
  565. default:
  566. return pref.ValueOf(int32(n))
  567. }
  568. case pref.Uint32Kind, pref.Fixed32Kind:
  569. switch n {
  570. case minVal:
  571. // Only use 0 for the zero value.
  572. return pref.ValueOf(uint32(1))
  573. case maxVal:
  574. return pref.ValueOf(uint32(math.MaxInt32))
  575. default:
  576. return pref.ValueOf(uint32(n))
  577. }
  578. case pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  579. switch n {
  580. case minVal:
  581. return pref.ValueOf(int64(math.MinInt64))
  582. case maxVal:
  583. return pref.ValueOf(int64(math.MaxInt64))
  584. default:
  585. return pref.ValueOf(int64(n))
  586. }
  587. case pref.Uint64Kind, pref.Fixed64Kind:
  588. switch n {
  589. case minVal:
  590. // Only use 0 for the zero value.
  591. return pref.ValueOf(uint64(1))
  592. case maxVal:
  593. return pref.ValueOf(uint64(math.MaxInt64))
  594. default:
  595. return pref.ValueOf(uint64(n))
  596. }
  597. case pref.FloatKind:
  598. switch n {
  599. case minVal:
  600. return pref.ValueOf(float32(math.SmallestNonzeroFloat32))
  601. case maxVal:
  602. return pref.ValueOf(float32(math.MaxFloat32))
  603. default:
  604. return pref.ValueOf(1.5 * float32(n))
  605. }
  606. case pref.DoubleKind:
  607. switch n {
  608. case minVal:
  609. return pref.ValueOf(float64(math.SmallestNonzeroFloat64))
  610. case maxVal:
  611. return pref.ValueOf(float64(math.MaxFloat64))
  612. default:
  613. return pref.ValueOf(1.5 * float64(n))
  614. }
  615. case pref.StringKind:
  616. if n == 0 {
  617. return pref.ValueOf("")
  618. }
  619. return pref.ValueOf(fmt.Sprintf("%d", n))
  620. case pref.BytesKind:
  621. if n == 0 {
  622. return pref.ValueOf([]byte(nil))
  623. }
  624. return pref.ValueOf([]byte{byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)})
  625. }
  626. panic("unhandled kind")
  627. }
  628. func populateMessage(m pref.Message, n seed, stack []pref.MessageDescriptor) pref.Value {
  629. if n == 0 {
  630. return pref.ValueOf(m)
  631. }
  632. md := m.Descriptor()
  633. for _, x := range stack {
  634. if md == x {
  635. return pref.ValueOf(m)
  636. }
  637. }
  638. stack = append(stack, md)
  639. for i := 0; i < md.Fields().Len(); i++ {
  640. fd := md.Fields().Get(i)
  641. if fd.IsWeak() {
  642. continue
  643. }
  644. m.Set(fd, newValue(m, fd, newSeed(n, i), stack))
  645. }
  646. return pref.ValueOf(m)
  647. }
  648. func panics(f func()) (didPanic bool) {
  649. defer func() {
  650. if err := recover(); err != nil {
  651. didPanic = true
  652. }
  653. }()
  654. f()
  655. return false
  656. }