github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/protobuf/plugin/deepcopy/deepcopytest.go (about) 1 package deepcopy 2 3 import ( 4 "github.com/gogo/protobuf/gogoproto" 5 "github.com/gogo/protobuf/plugin/testgen" 6 "github.com/gogo/protobuf/protoc-gen-gogo/generator" 7 ) 8 9 type test struct { 10 *generator.Generator 11 } 12 13 // NewTest creates a new deepcopy testgen plugin 14 func NewTest(g *generator.Generator) testgen.TestPlugin { 15 return &test{g} 16 } 17 18 func (p *test) Generate(imports generator.PluginImports, file *generator.FileDescriptor) bool { 19 used := false 20 testingPkg := imports.NewImport("testing") 21 randPkg := imports.NewImport("math/rand") 22 timePkg := imports.NewImport("time") 23 24 for _, message := range file.Messages() { 25 if !gogoproto.HasTestGen(file.FileDescriptorProto, message.DescriptorProto) { 26 continue 27 } 28 29 if message.DescriptorProto.GetOptions().GetMapEntry() { 30 continue 31 } 32 33 used = true 34 ccTypeName := generator.CamelCaseSlice(message.TypeName()) 35 p.P() 36 p.P(`func Test`, ccTypeName, `Copy(t *`, testingPkg.Use(), `.T) {`) 37 p.In() 38 p.P(`popr := `, randPkg.Use(), `.New(`, randPkg.Use(), `.NewSource(`, timePkg.Use(), `.Now().UnixNano()))`) 39 p.P(`in := NewPopulated`, ccTypeName, `(popr, true)`) 40 p.P(`out := in.Copy()`) 41 p.P(`if !in.Equal(out) {`) 42 p.In() 43 p.P(`t.Fatalf("%#v != %#v", in, out)`) 44 p.Out() 45 p.P(`}`) 46 47 for _, f := range message.Field { 48 fName := generator.CamelCase(*f.Name) 49 if gogoproto.IsCustomName(f) { 50 fName = gogoproto.GetCustomName(f) 51 } 52 53 if f.OneofIndex != nil { 54 fName = "Get" + fName + "()" 55 if f.IsMessage() { 56 p.P(`if in.`, fName, ` != nil && in.`, fName, ` == out.`, fName, ` {`) 57 p.In() 58 p.P(`t.Fatalf("`, fName, `: %#v == %#v", in.`, fName, `, out.`, fName, `)`) 59 p.Out() 60 p.P(`}`) 61 } 62 } else { 63 p.P(`if &in.`, fName, ` == &out.`, fName, ` {`) 64 p.In() 65 p.P(`t.Fatalf("`, fName, `: %#v == %#v", &in.`, fName, `, &out.`, fName, `)`) 66 p.Out() 67 p.P(`}`) 68 } 69 70 if f.IsBytes() { 71 if f.IsRepeated() { 72 p.P(`if len(in.`, fName, `) > 0 {`) 73 p.In() 74 fName += "[0]" 75 } 76 p.P(`if len(in.`, fName, `) > 0 {`) 77 p.In() 78 p.P(`in.`, fName, "[0]++") 79 p.P(`if in.Equal(out) {`) 80 p.In() 81 p.P(`t.Fatalf("%#v == %#v", in, out)`) 82 p.Out() 83 p.P(`}`) 84 p.Out() 85 p.P(`}`) 86 if f.IsRepeated() { 87 p.Out() 88 p.P(`}`) 89 } 90 } 91 } 92 93 // copying from nil should result in nil 94 p.P() 95 p.P(`in = nil`) 96 p.P(`out = in.Copy()`) 97 p.P(`if out != nil {`) 98 p.In() 99 p.P(`t.Fatalf("copying nil should return nil, returned: %#v", out)`) 100 p.Out() 101 p.P(`}`) 102 103 p.Out() 104 p.P(`}`) 105 } 106 107 return used 108 } 109 110 func init() { 111 testgen.RegisterTestPlugin(NewTest) 112 }