无法断言时间戳。

huangapple go评论83阅读模式
英文:

Unable to assert timestamps

问题

我有一个从表中检索用户的postgres方法。这是方法的代码:

func FindUsers() ([]User, error) {
    var users []User

    if err := db.Model(User{}).Find(&users).Error; err != nil {
        return nil, err
    }
    return users, nil
}

这是User模型:

type User struct {
    ID        uint       `gorm:"primarykey"`
    CreatedAt time.Time  `gorm:"not null"`
}

我试图断言这个方法按预期工作:

func (suite *TestSuite) TestFindUsers() {
    dateString := "2023-05-25"  // 日期字符串格式为"YYYY-MM-DD"

    // 解析日期字符串
    date, err := time.Parse("2006-01-02", dateString)
    if err != nil {
        //
    }
    existingUser := User{
        ID:        1,
        CreatedAt: date,
    }
    suite.DB.Create(existingUser)
    users, err := suite.repository.FindUsers()
    assert.NoError(suite.T(), err)
    assert.Equal(suite.T(), date, users[0].CreatedAt)
}

当我运行测试时,我得到了这个错误:

Error:      	Not equal: 
                	expected: time.Date(2023, time.May, 25, 0, 0, 0, 0, time.UTC)
                	actual  : time.Date(2023, time.May, 25, 0, 0, 0, 0, time.UTC)
                	
                	Diff:

我不确定还能做什么。

英文:

I have a postgres method that retrieves users from a table. This is the method -

func FindUsers() ([]User, error) {
	var users []User

	if err := db.Model(User{}).Find(&users).Error; err != nil {
		return nil, err
	}
	return users, nil
}

This is the User model

type User struct {
	ID            uint            `gorm:"primarykey"`
	CreatedAt     time.Time `gorm:"not null"`
}

I try to assert that this method works as expected,

func (suite *TestSuite) TestFindUsers() {
dateString := "2023-05-25"  // Date string in the format "YYYY-MM-DD"

	// Parse the date string
	date, err := time.Parse("2006-01-02", dateString)
	if err != nil {
		//
	}
    existingUser := User {
      ID: 1,
      CreatedAt:     date,
    }
    suite.DB.Create(existingUser) 
    users, err := suite.repository.FindUsers()
    assert.NoError(suite.T(), err)
    assert.Equal(suite.T(), date, users[0].CreatedAt)
}

I get this error when I run the test,

Error:      	Not equal: 
                	expected: time.Date(2023, time.May, 25, 0, 0, 0, 0, time.UTC)
                	actual  : time.Date(2023, time.May, 25, 0, 0, 0, 0, time.UTC)
                	
                	Diff:

I am not sure what else to do here.

答案1

得分: 2

你不能对time.Time的值使用相等性操作(因此也不能使用assert.Equal()),详细信息请参见https://stackoverflow.com/questions/36614921/why-do-2-time-structs-with-the-same-date-and-time-return-false-when-compared-wit/36615458#36615458

如果时间实例必须相同,你可以使用Time.Equal()的结果以及assert.True()

assert.True(suite.T(), date.Equal(users[0].CreatedAt))

另一种方法是使用Time.Unix()(返回int64值)或Time.UnixNano()获取这些值的Unix时间,并进行比较:

assert.Equal(suite.T(), date.Unix(), users[0].CreatedAt.Unix())

或者,如果时间实例不必相同(但是“非常”接近),你可以使用assert.WithinDuration(),例如:

assert.WithinDuration(suite.T(), date, users[0].CreatedAt, 10*time.Millisecond)
英文:

You can't use equality on time.Time values (and therefore assert.Equal()), for details, see https://stackoverflow.com/questions/36614921/why-do-2-time-structs-with-the-same-date-and-time-return-false-when-compared-wit/36615458#36615458

If the time instances must be the same, you may use the result of Time.Equal() along with assert.True():

assert.True(suite.T(), date.Equal(users[0].CreatedAt))

Another way is to get the Unix time of those values using Time.Unix() (which is an int64 value) or Time.UnixNano(), and compare those:

assert.Equal(suite.T(), date.Unix(), users[0].CreatedAt.Unix())

Or if the time instances must not be the same (but "very" close to each other), you may use assert.WithinDuration(), e.g.:

assert.WithinDuration(suite.T(), date, users[0].CreatedAt, 10*time.Millisecond)

huangapple
  • 本文由 发表于 2023年5月25日 15:23:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76329791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定