repogen/internal/codegen/builder_test.go

126 lines
2.5 KiB
Go
Raw Permalink Normal View History

package codegen_test
import (
"testing"
2023-05-24 11:04:29 +00:00
"git.kmsign.ru/royalcat/repogen/internal/code"
"git.kmsign.ru/royalcat/repogen/internal/codegen"
"git.kmsign.ru/royalcat/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",
},
Tag: `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: codegen.FunctionBody{
codegen.ReturnStatement{
codegen.StructStatement{
Type: "User",
Pairs: []codegen.StructFieldPair{
{
Key: "ID",
Value: codegen.ChainStatement{
codegen.Identifier("primitive"),
codegen.CallStatement{
FuncName: "NewObjectID",
},
},
},
{
Key: "Username",
Value: codegen.Identifier("username"),
},
},
},
},
},
})
builder.AddImplementer(codegen.MethodBuilder{
Receiver: codegen.MethodReceiver{Name: "u", Type: code.SimpleType("User")},
Name: "IDHex",
Params: nil,
Returns: []code.Type{code.TypeString},
Body: codegen.FunctionBody{
codegen.ReturnStatement{
codegen.ChainStatement{
codegen.Identifier("u"),
codegen.Identifier("ID"),
codegen.CallStatement{FuncName: "Hex"},
},
},
},
})
generatedCode, err := builder.Build()
if err != nil {
t.Fatal(err)
}
if err := testutils.ExpectMultiLineString(expectedBuildCode, generatedCode); err != nil {
t.Error(err)
}
}