postgresql Go Lang单元测试

szqfcxe2  于 2023-10-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(121)

在运行单元测试时获取主键冲突user_id的错误
我的togglefavorite函数如下

func ToggleTrackToFavourite(c *gin.Context) {
    userID := GetCurrentUserID(c)
    trackID, err := strconv.Atoi(c.Param("id"))
    if err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Track ID"})
        return
    }
    if err := favourites.CreateTable(db.DB); err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create table" + err.Error()})
        return
    }
    if isInFavorites(userID, trackID) {
        err = favourites.RemoveFavorite(db.DB, userID, trackID)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to remove track from favorites"})
            return
        }

        c.JSON(http.StatusOK, gin.H{"message": "Track removed from favorites"})
    } else {
        err = favourites.InsertFavorite(db.DB, userID, trackID)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to add track to favorites : " + err.Error()})
            return
        }

        c.JSON(http.StatusOK, gin.H{"message": "Track added to favorites"})
    }
}
func GetCurrentUserID(c *gin.Context) int {
    userID, exists := c.Get("userID")
    if !exists {
        return 0
    }
    if userIDInt, ok := userID.(int); ok {
        return userIDInt
    }
    return 0
}

我对上面代码的单元测试函数如下

func TestToggleTrackToFavourite(t *testing.T) {
    db.InitTestDB()

    if err := users.CreateTable(db.DB); err != nil {
        t.Fatalf("Failed to create users table: %v", err)
    }
    if err := tracks.CreateTable(db.DB); err != nil {
        t.Fatalf("Failed to create tracks table: %v", err)
    }
    if err := favourites.CreateTable(db.DB); err != nil {
        t.Fatalf("Failed to create favorites table: %v", err)
    }
    user := users.User{
        Username: "Test",
        Email:    "[email protected]",
        Password: "123456",
    }
    if err := users.CreateUser(db.DB, &user); err != nil {
        t.Fatalf("Failed to create user: %v", err)
    }

    sampleTrack := tracks.Track{
        Name:         "Test track",
        Index:        10,
        Track:        "chere.mp4",
        Image:        "image.jpg",
        Album_ID:     4,
        Is_Published: true,
    }
    if err := tracks.CreateTrack(db.DB, &sampleTrack); err != nil {
        t.Fatalf("Failed to insert the example track: %v", err)
    }

    r := gin.Default()
    r.PUT("/user/favorite/toggle/:id", ToggleTrackToFavourite)

    reqAddToFavorites := httptest.NewRequest("PUT", "/user/favorite/toggle/1", nil)
    wAddToFavorites := httptest.NewRecorder()

    r.ServeHTTP(wAddToFavorites, reqAddToFavorites)
    assert.Equal(t, http.StatusOK, wAddToFavorites.Code)
    assert.Equal(t, `{"message":"Track added to favorites"}`, wAddToFavorites.Body.String())

    // reqRemoveFromFavorites := httptest.NewRequest("PUT", "/user/favorite/toggle/1", nil)
    // reqAddToFavorites.Params = append(reqAddToFavorites.Params, httptest.Param{"id", "1"})
    // wRemoveFromFavorites := httptest.NewRecorder()
    // r.ServeHTTP(wRemoveFromFavorites, reqRemoveFromFavorites)
    // assert.Equal(t, http.StatusOK, wRemoveFromFavorites.Code)
    // assert.Equal(t, `{"message":"Track removed from favorites"}`, wRemoveFromFavorites.Body.String())

    if _, err := db.DB.Exec("DROP TABLE IF EXISTS favorite"); err != nil {
        t.Fatalf("Failed to drop the table: %v", err)
    }
    if _, err := db.DB.Exec("DROP TABLE IF EXISTS tracks"); err != nil {
        t.Fatalf("Failed to drop the table: %v", err)
    }
    if _, err := db.DB.Exec("DROP TABLE IF EXISTS users"); err != nil {
        t.Fatalf("Failed to drop the table: %v", err)
    }
}

不知道如何在单元测试中将GETCURRENTUSER函数的默认值作为1传递
想要添加/删除收藏夹中的曲目

vc9ivgsu

vc9ivgsu1#

看起来你的代码中的用户id存储在你的处理程序之前的一些认证中间件的上下文局部变量中名为“userId”的局部变量中,所以设置它就足够测试了,你可以修改这些行:

r := gin.Default()
    c.Set("userID", "1")
    r.PUT("/user/favorite/toggle/:id", ToggleTrackToFavourite)

相关问题