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