list_people_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package main
  2. import (
  3. "bytes"
  4. "strings"
  5. "testing"
  6. pb "github.com/google/protobuf/examples/tutorial"
  7. )
  8. func TestListPeopleWritesList(t *testing.T) {
  9. buf := new(bytes.Buffer)
  10. in := pb.AddressBook{[]*pb.Person{
  11. {
  12. Name: "John Doe",
  13. Id: 101,
  14. Email: "john@example.com",
  15. },
  16. {
  17. Name: "Jane Doe",
  18. Id: 102,
  19. },
  20. {
  21. Name: "Jack Doe",
  22. Id: 201,
  23. Email: "jack@example.com",
  24. Phones: []*pb.Person_PhoneNumber{
  25. {Number: "555-555-5555", Type: pb.Person_WORK},
  26. },
  27. },
  28. {
  29. Name: "Jack Buck",
  30. Id: 301,
  31. Email: "buck@example.com",
  32. Phones: []*pb.Person_PhoneNumber{
  33. {Number: "555-555-0000", Type: pb.Person_HOME},
  34. {Number: "555-555-0001", Type: pb.Person_MOBILE},
  35. {Number: "555-555-0002", Type: pb.Person_WORK},
  36. },
  37. },
  38. {
  39. Name: "Janet Doe",
  40. Id: 1001,
  41. Email: "janet@example.com",
  42. Phones: []*pb.Person_PhoneNumber{
  43. {Number: "555-777-0000"},
  44. {Number: "555-777-0001", Type: pb.Person_HOME},
  45. },
  46. },
  47. }}
  48. listPeople(buf, &in)
  49. want := strings.Split(`Person ID: 101
  50. Name: John Doe
  51. E-mail address: john@example.com
  52. Person ID: 102
  53. Name: Jane Doe
  54. Person ID: 201
  55. Name: Jack Doe
  56. E-mail address: jack@example.com
  57. Work phone #: 555-555-5555
  58. Person ID: 301
  59. Name: Jack Buck
  60. E-mail address: buck@example.com
  61. Home phone #: 555-555-0000
  62. Mobile phone #: 555-555-0001
  63. Work phone #: 555-555-0002
  64. Person ID: 1001
  65. Name: Janet Doe
  66. E-mail address: janet@example.com
  67. Mobile phone #: 555-777-0000
  68. Home phone #: 555-777-0001
  69. `, "\n")
  70. got := strings.Split(buf.String(), "\n")
  71. if len(got) != len(want) {
  72. t.Errorf(
  73. "listPeople(%s) =>\n\t%q has %d lines, want %d",
  74. in.String(),
  75. buf.String(),
  76. len(got),
  77. len(want))
  78. }
  79. lines := len(got)
  80. if lines > len(want) {
  81. lines = len(want)
  82. }
  83. for i := 0; i < lines; i++ {
  84. if got[i] != want[i] {
  85. t.Errorf(
  86. "listPeople(%s) =>\n\tline %d %q, want %q",
  87. in.String(),
  88. i,
  89. got[i],
  90. want[i])
  91. }
  92. }
  93. }