package codegen_test import ( "testing" "github.com/sunboyy/repogen/internal/code" "github.com/sunboyy/repogen/internal/codegen" "github.com/sunboyy/repogen/internal/testutils" ) const expectedBuildCode = `// Code generated by repogen. DO NOT EDIT. package user import ( _ "context" "go.mongodb.org/mongo-driver/bson/primitive" _ "go.mongodb.org/mongo-driver/mongo/options" ) type User struct { ID primitive.ObjectID ` + "`bson:\"id\" json:\"id,omitempty\"`" + ` Username string } func NewUser(username string) User { return User{ ID: primitive.NewObjectID(), Username: username, } } func (u User) IDHex() string { return u.ID.Hex() } ` func TestBuilderBuild(t *testing.T) { builder := codegen.NewBuilder("repogen", "user", [][]code.Import{ { { Name: "_", Path: "context", }, }, { { Path: "go.mongodb.org/mongo-driver/bson/primitive", }, { Name: "_", Path: "go.mongodb.org/mongo-driver/mongo/options", }, }, }) builder.AddImplementer(codegen.StructBuilder{ Name: "User", Fields: code.StructFields{ { Name: "ID", Type: code.ExternalType{ PackageAlias: "primitive", Name: "ObjectID", }, Tags: map[string][]string{ "bson": {"id"}, "json": {"id", "omitempty"}, }, }, { Name: "Username", Type: code.TypeString, }, }, }) builder.AddImplementer(codegen.FunctionBuilder{ Name: "NewUser", Params: []code.Param{ {Name: "username", Type: code.TypeString}, }, Returns: []code.Type{code.SimpleType("User")}, Body: ` return User{ ID: primitive.NewObjectID(), Username: username, }`, }) builder.AddImplementer(codegen.MethodBuilder{ Receiver: codegen.MethodReceiver{Name: "u", Type: code.SimpleType("User")}, Name: "IDHex", Params: nil, Returns: []code.Type{code.TypeString}, Body: " return u.ID.Hex()", }) generatedCode, err := builder.Build() if err != nil { t.Fatal(err) } if err := testutils.ExpectMultiLineString(expectedBuildCode, generatedCode); err != nil { t.Error(err) } }