1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| package main
import ( "io/ioutil" "log" "os" "testing"
"github.com/pkg/errors" . "github.com/smartystreets/goconvey/convey" "gorm.io/driver/sqlite" "gorm.io/gorm" )
const dbFile = "./test.db"
var db *gorm.DB
func TestMain(m *testing.M) { if err := InitSQLite(); err != nil { log.Fatal(err) } if err := ExecSQLite("test.sql"); err != nil { log.Fatal(err) } code := m.Run() if err := DelSQLite(); err != nil { log.Fatal(err) } os.Exit(code) }
func InitSQLite() error { if err := DelSQLite(); err != nil { return err } var err error db, err = gorm.Open(sqlite.Open(dbFile), &gorm.Config{}) if err != nil { return errors.Wrap(err, "init sqlite error") } if err := db.AutoMigrate(&SettleItem{}); err != nil { return errors.Wrap(err, "init sqlite error") } if err := db.AutoMigrate(&SettleRule{}); err != nil { return errors.Wrap(err, "init sqlite error") } return nil }
func ExecSQLite(sqlFile string) error { data, err := ioutil.ReadFile(sqlFile) if err != nil { return errors.Wrap(err, "exec sqlite error") } s := string(data) if err := db.Exec(s).Error; err != nil { return errors.Wrap(err, "exec sqlite error") } return nil }
func DelSQLite() error { if _, err := os.Stat(dbFile); os.IsNotExist(err) { return nil } err := os.Remove(dbFile) if err != nil { return errors.Wrap(err, "del sqlite error") } return nil }
func TestNewSettle(t *testing.T) { Convey("NewSettle", t, func() { obj := NewSettle(db) So(obj, ShouldNotBeNil) }) }
func Test_settle_GetSettleItem(t *testing.T) { Convey("GetSettleItem", t, func() { obj := NewSettle(db) i, err := obj.GetSettleItem(1) So(err, ShouldBeNil) So(i.Name, ShouldEqual, "1") }) Convey("GetSettleItem not found", t, func() { obj := NewSettle(db) _, err := obj.GetSettleItem(2) So(errors.Is(err, gorm.ErrRecordNotFound), ShouldEqual, true) }) }
func Test_settle_GetSettleRule(t *testing.T) { Convey("GetSettleRule", t, func() { obj := NewSettle(db) i, err := obj.GetSettleRule(1) So(err, ShouldBeNil) So(i.Price, ShouldEqual, 1) }) Convey("GetSettleRule not found", t, func() { obj := NewSettle(db) _, err := obj.GetSettleRule(2) So(errors.Is(err, gorm.ErrRecordNotFound), ShouldEqual, true) }) }
|