DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.05k stars 406 forks source link

different results after several execution of the same tests #238

Closed crevillo closed 3 years ago

crevillo commented 3 years ago

hello. probably not an issue and this is something i'm doing wrong, but not sure where to ask for support.

i'm working with gorm and one of my repos has this method

func (licenseRepository *licenseRepository) GetLicenses(license *domain.License) ([]domain.License, error) {
    var licenses []domain.License

    err := licenseRepository.db.Debug().Where(&license).Preload("Roles").Find(&licenses).Error

    if err != nil {
        return nil, err
    }

    return licenses, nil
}

i'm writing a test for that method. test looks like

func (s *Suite) Test_licenseRepository_GetLicenses() {
    s.mock.ExpectQuery(
        `SELECT \* FROM "licenses" WHERE "licenses"\."deleted_at" IS NULL`,
    ).WillReturnRows(sqlmock.NewRows([]string{
        "id", "code",
    }).AddRow(
        3,
        "code1",
    ).AddRow(
        4,
        "code2",
    ))

    s.mock.ExpectQuery(
        `SELECT \* FROM "roles"  WHERE "roles"\."deleted_at" IS NULL AND \(\("license_id" IN \(\$1,\$2\)\)\)`,
    ).WithArgs(3, 4).WillReturnRows(sqlmock.NewRows([]string{
        "id", "code",
    }).AddRow(2, "role1"))

    licenses, err := s.licenseRepository.GetLicenses(&domain.License{})

    require.NoError(s.T(), err)
    require.Equal(s.T(), 2, len(licenses))
    require.Equal(s.T(), "code2", licenses[1].Code)
}

this tests looks passing if i try go test -v ./repository but, i I repeat the operation several times, i have fails and passes. I don't know where the problem could be. the only thing i can see is that when the test fails, the output says

        licenserepository_test.go:92: 
                Error Trace:    licenserepository_test.go:92
                Error:          Received unexpected error:
                                Query 'SELECT * FROM "roles"  WHERE "roles"."deleted_at" IS NULL AND (("license_id" IN ($1,$2)))', arguments do not match: argument 0 expected [int64 - 3] does not match actual [int64 - 4]

meaning that for some reason, for the second query i'm testing there, the params seem to be switched when the test fail. anyone have seem something like this? Thanks.

crevillo commented 3 years ago

I'm gonna to close this. Looks problem is not the go-sqlmock but gorm or something else. i tried the endpoint that uses these repository several times and i can see that in that second query the values passed to the IN part differ from one execution to another. sorry about the noise.