codegen: improve the "TestFkChecking" generated function
All checks were successful
CI / build-docker (push) Successful in 6s
CI / build-docker-bootstrap (push) Has been skipped
CI / release-test (push) Successful in 3m22s

This commit is contained in:
~wispem-wantex 2026-02-14 18:33:41 -08:00
parent 8c29d455ff
commit 9a11f3986c

View File

@ -297,25 +297,35 @@ func GenerateModelTestAST(tbl pkgschema.Table, schema pkgschema.Schema, gomodNam
Name: ast.NewIdent("Test" + tbl.GoTypeName + "FkChecking"), Name: ast.NewIdent("Test" + tbl.GoTypeName + "FkChecking"),
Type: testFuncType, Type: testFuncType,
Body: &ast.BlockStmt{ Body: &ast.BlockStmt{
List: func() []ast.Stmt { List: func() (stmts []ast.Stmt) {
isFirst := true
for _, col := range tbl.Columns {
if !col.IsForeignKey {
continue
}
shouldIncludeTestFkCheck = true
// post := MakePost() // post := MakePost()
stmts := []ast.Stmt{ if !isFirst {
stmts = append(stmts, BlankLine())
}
stmts = append(stmts, []ast.Stmt{
// Comment header
Comment(fmt.Sprintf("Invalid %s", col.GoFieldName())),
// `Invalid BlahBlahID`
&ast.AssignStmt{ &ast.AssignStmt{
Lhs: []ast.Expr{ast.NewIdent(tbl.VarName)}, Lhs: []ast.Expr{ast.NewIdent(tbl.VarName)},
Tok: token.DEFINE, Tok: map[bool]token.Token{true: token.DEFINE, false: token.ASSIGN}[isFirst],
Rhs: []ast.Expr{ Rhs: []ast.Expr{
&ast.CallExpr{ &ast.CallExpr{
Fun: ast.NewIdent("Make" + tbl.GoTypeName), Fun: ast.NewIdent("Make" + tbl.GoTypeName),
}, },
}, },
}, },
}
shouldDefineErr := true // `post.QuotedPostID = 94354538969386985`
for _, col := range tbl.Columns {
if col.IsForeignKey {
shouldIncludeTestFkCheck = true
stmts = append(stmts, []ast.Stmt{
// post.QuotedPostID = 94354538969386985
&ast.AssignStmt{ &ast.AssignStmt{
Lhs: []ast.Expr{ Lhs: []ast.Expr{
&ast.SelectorExpr{ &ast.SelectorExpr{
@ -332,10 +342,10 @@ func GenerateModelTestAST(tbl pkgschema.Table, schema pkgschema.Schema, gomodNam
}, },
}, },
// err := db.SavePost(&post) // `err := db.SavePost(&post)`
&ast.AssignStmt{ &ast.AssignStmt{
Lhs: []ast.Expr{ast.NewIdent("err")}, Lhs: []ast.Expr{ast.NewIdent("err")},
Tok: map[bool]token.Token{true: token.DEFINE, false: token.ASSIGN}[shouldDefineErr], Tok: map[bool]token.Token{true: token.DEFINE, false: token.ASSIGN}[isFirst],
Rhs: []ast.Expr{ Rhs: []ast.Expr{
&ast.CallExpr{ &ast.CallExpr{
Fun: &ast.SelectorExpr{ Fun: &ast.SelectorExpr{
@ -352,7 +362,7 @@ func GenerateModelTestAST(tbl pkgschema.Table, schema pkgschema.Schema, gomodNam
}, },
}, },
// assertForeignKeyError(t, err, "QuotedPostID", post.QuotedPostID) // `assertForeignKeyError(t, err, "QuotedPostID", post.QuotedPostID)`
&ast.ExprStmt{ &ast.ExprStmt{
X: &ast.CallExpr{ X: &ast.CallExpr{
Fun: ast.NewIdent("AssertForeignKeyError"), Fun: ast.NewIdent("AssertForeignKeyError"),
@ -371,8 +381,7 @@ func GenerateModelTestAST(tbl pkgschema.Table, schema pkgschema.Schema, gomodNam
}, },
}, },
}...) }...)
shouldDefineErr = false isFirst = false
}
} }
return stmts return stmts
}(), }(),