gen
gen copied to clipboard
GEN Generate unique aware unit tests.
Describe the feature
Currently, when gen generate unittests files, it uses a fixed template:
err = _do.Create(&{{.StructInfo.Package}}.{{.ModelStructName}}{})
if err != nil {
t.Error("create item in table <{{.TableName}}> fail:", err)
}
err = _do.Save(&{{.StructInfo.Package}}.{{.ModelStructName}}{})
if err != nil {
t.Error("create item in table <{{.TableName}}> fail:", err)
}
err = _do.CreateInBatches([]*{{.StructInfo.Package}}.{{.ModelStructName}}{ {}, {} }, 10)
if err != nil {
t.Error("create item in table <{{.TableName}}> fail:", err)
}
which generates codes like(e.g. for a Worker
model):
err = _do.Create(&model.Worker{})
if err != nil {
t.Error("create item in table <workers> fail:", err)
}
err = _do.Save(&model.Worker{})
if err != nil {
t.Error("create item in table <workers> fail:", err)
}
err = _do.CreateInBatches([]*model.Worker{{}, {}}, 10)
if err != nil {
t.Error("create item in table <workers> fail:", err)
}
But if worker has a unique column, the test codes try to insert 4 record have same column ( i.e. "") , that will break the test.
A previous issue someone sugguest modify generated codes, which I dont' think is a good idea. People may integrate code generate script into their CICD pipeline that hard to modify codes.
Since the complete model info were given when rendering codes, which lies in QueryStructMeta.Fields.GORMTag
,
I believe it's approchable to generate unique aware test codes.
If there're unique columns in a model, just skip the later two Save
and CreateInBatches
statements should be ok.
A better approch is to assign random values to each record, but that will be too complicated to implement, especailly there're composite unique indexes.