1

我们花了 2 周令人沮丧的时间尝试使用 sqlmock 对函数和方法进行所有可能的排列,但无法对 INSERT 语句进行测试。这是非常基本的妈妈和流行 SQL。只需使用 Gorm 进行简单的插入。

太多的代码要发布,还有很多错误的排列方式和方法要在这里列出,但我会发布最新的。

type AnyTime struct{}

func (a AnyTime) Match(v driver.Value) bool {
    _, ok := v.(time.Time)
    return ok
}

func TestInsertStoragePool(t *testing.T) {

    cases := []struct {
        givenPool    StoragePool
        wantedError  error
    }{
        {
            givenPool: StoragePool{
                Name:   "POOL1",
                PoolId: "1",
                Type:   "NetworkFilesystem",
                Volumes: []Volume{
                    {
                        Name:      "VOL01",
                        StorageId: "1",
                        Type:      "ROOT",
                        VolumeId:  "1",
                    },
                },
            },
            wantedError: nil,
        },
    }

    for _, c := range cases {

        db, mock, err := sqlmock.New()
        if err != nil {
            t.Fatal(err)
        }

        // Every attempt we make we try "Postgres", "mysql" and "sqlite3" here
        DB, err := gorm.Open("sqlite3", db)
        if err != nil {
            t.Fatal(err)
        }
        DB.LogMode(true)

        mock.ExpectBegin()
        mock.ExpectExec(`INSERT INTO "storage_pools"`).WithArgs(
            AnyTime{},
            AnyTime{},
            nil,
            0,
            0,
            "",
            "",
            "",
            0,
            0,
            0,
            "",
            c.givenPool.Name,
            "",
            0,
            "",
            "",
            c.givenPool.PoolId,
            "",
            "",
            "",
            c.givenPool.Type,
            "",
            "").WillReturnResult(sqlmock.NewResult(1, 1))

        mock.ExpectCommit()

        err = InsertStoragePool(DB, &c.givenPool)
        if err != nil {
            fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
        }

        if !reflect.DeepEqual(err, c.wantedError) {
            t.Errorf("expecting errror %q, got %q", c.wantedError, err)
        }

    }

}

这次尝试的错误:

$go test ./...

(/database.go:231)
[2019-12-13 09:22:48]  [0.11ms]  INSERT  INTO "storage_pools" ("created_at","updated_at","deleted_at","allocatediops","capacityiops","clusterid","clustername","created","disksizeallocated","disksizetotal","disksizeused","ipaddress","name","path","physicalsize","podid","podname","poolid","provider","scope","state","type","zoneid","zonename") VALUES ('2019-12-13 09:22:48','2019-12-13 09:22:48',NULL,0,0,'','','',0,0,0,'','POOL1','',0,'','','1','','','','NetworkFilesystem','','')
[1 rows affected or returned ]

(/database.go:231)
[2019-12-13 09:22:48]  call to ExecQuery 'INSERT  INTO "volumes" ("created_at","updated_at","deleted_at","clusterid","clustername","domainid","domain","name","path","physicalsize","podid","podname","size","state","storageid","storage","type","virtualsize","virtualmachineid","vmdisplayname","vmname","vmstate","volumeid","zoneid","zonename") VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)' with args [{Name: Ordinal:1 Value:2019-12-13 09:22:48.093749 -0800 PST m=+0.004941653} {Name: Ordinal:2 Value:2019-12-13 09:22:48.093749 -0800 PST m=+0.004941653} {Name: Ordinal:3 Value:<nil>} {Name: Ordinal:4 Value:} {Name: Ordinal:5 Value:} {Name: Ordinal:6 Value:} {Name: Ordinal:7 Value:} {Name: Ordinal:8 Value:VOL01} {Name: Ordinal:9 Value:} {Name: Ordinal:10 Value:0} {Name: Ordinal:11 Value:} {Name: Ordinal:12 Value:} {Name: Ordinal:13 Value:0} {Name: Ordinal:14 Value:} {Name: Ordinal:15 Value:1} {Name: Ordinal:16 Value:} {Name: Ordinal:17 Value:ROOT} {Name: Ordinal:18 Value:0} {Name: Ordinal:19 Value:} {Name: Ordinal:20 Value:} {Name: Ordinal:21 Value:} {Name: Ordinal:22 Value:} {Name: Ordinal:23 Value:1} {Name: Ordinal:24 Value:} {Name: Ordinal:25 Value:}], was not expected, next expectation is: ExpectedCommit => expecting transaction Commit
4

1 回答 1

3

错误消息告诉您在您预期的插入之后执行了额外的插入:

INSERT INTO "volumes" (.....) 不是预期的,下一个预期是:ExpectedCommit

在您的代码中,我们可以看到您的结构在切片StoragePool中也有一些内部。Volumes

所以可能当你打电话时InsertStoragePool,首先插入一行storage_pools,然后volumes插入。

在添加对提交的期望之前,您应该为该插入添加一个新的期望。

于 2019-12-13T17:39:10.033 回答