repogen/internal/codegen/builder_test.go
2023-04-19 19:42:08 +07:00

125 lines
2.5 KiB
Go

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",
},
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)
}
}