92 lines
2.3 KiB
Go
92 lines
2.3 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
DB "log101-blog-services/db"
|
|
"log101-blog-services/models"
|
|
"log101-blog-services/utils"
|
|
)
|
|
|
|
func TestGetEmojiForm(t *testing.T) {
|
|
db := utils.SetupTestDB()
|
|
DB.SetDB(db)
|
|
|
|
router := gin.Default()
|
|
router.LoadHTMLGlob("../templates/*")
|
|
|
|
router.GET("/emoji_form", GetEmojiForm)
|
|
|
|
req, _ := http.NewRequest("GET", "/emoji_form?postId=1", nil)
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, req)
|
|
|
|
assert.Equal(t, http.StatusOK, w.Code)
|
|
assert.Contains(t, w.Body.String(), "👍")
|
|
assert.Contains(t, w.Body.String(), "😑")
|
|
}
|
|
|
|
func TestPostEmojiForm(t *testing.T) {
|
|
db := utils.SetupTestDB()
|
|
DB.SetDB(db) // Set the mock DB
|
|
|
|
router := gin.Default()
|
|
router.LoadHTMLGlob("../templates/*")
|
|
|
|
router.POST("/emoji_form", PostEmojiForm)
|
|
|
|
form := url.Values{}
|
|
form.Add("postId", "1")
|
|
form.Add("emojiInput", "👍")
|
|
|
|
req, _ := http.NewRequest("POST", "/emoji_form", strings.NewReader(form.Encode()))
|
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, req)
|
|
|
|
assert.Equal(t, http.StatusOK, w.Code)
|
|
assert.Contains(t, w.Body.String(), "👍 1")
|
|
}
|
|
|
|
func TestPostEmojiFormMissingParams(t *testing.T) {
|
|
db := utils.SetupTestDB()
|
|
DB.SetDB(db) // Set the mock DB
|
|
|
|
router := gin.Default()
|
|
router.LoadHTMLGlob("../templates/*") // Ensure you have your templates in the right path
|
|
|
|
router.POST("/emoji_form", PostEmojiForm)
|
|
|
|
form := url.Values{}
|
|
form.Add("postId", "1")
|
|
|
|
req, _ := http.NewRequest("POST", "/emoji_form", strings.NewReader(form.Encode()))
|
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
|
w := httptest.NewRecorder()
|
|
router.ServeHTTP(w, req)
|
|
|
|
assert.Equal(t, http.StatusBadRequest, w.Code)
|
|
assert.Contains(t, w.Body.String(), "missing parameters")
|
|
}
|
|
|
|
func TestGetEmojis(t *testing.T) {
|
|
db := utils.SetupTestDB()
|
|
DB.SetDB(db) // Set the mock DB
|
|
|
|
// Populate the test database with data
|
|
db.Create(&models.EmojiReaction{UserAnonIp: "127.0.0.2", Emoji: "😊", PostId: "1"})
|
|
db.Create(&models.EmojiReaction{UserAnonIp: "127.0.0.1", Emoji: "😂", PostId: "1"})
|
|
|
|
counts, err := GetEmojis("1")
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, 1, counts["😊"])
|
|
assert.Equal(t, 1, counts["😂"])
|
|
}
|