Files
old-backend/controllers/devices_controller_test.go

84 lines
2.1 KiB
Go
Raw Normal View History

2023-09-27 08:04:50 +02:00
package controllers_test
2023-09-13 21:54:43 +02:00
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"gitlab.com/pactual1/backend/config"
2023-09-27 08:04:50 +02:00
"gitlab.com/pactual1/backend/controllers"
"gitlab.com/pactual1/backend/routes"
2023-09-13 21:54:43 +02:00
"gitlab.com/pactual1/backend/shared"
)
// Assume setupServer() returns your gin.Engine instance
func runTestServer() *httptest.Server {
// Initialize your database or any other setup
// For the sake of this example, I'll just return the Gin engine
// LOAD APPLICATION CONFIGURATION
err := config.Load()
if err != nil {
log.Fatal(err)
}
2023-09-18 12:27:40 +02:00
2023-09-13 21:54:43 +02:00
shared.Init()
r := gin.Default()
2023-09-27 08:04:50 +02:00
r.POST("/device_info", controllers.SaveDeviceInfo)
routes.RegisterPublicRoutes(r)
2023-09-13 21:54:43 +02:00
return httptest.NewServer(r)
}
func TestSaveDeviceInfofunc(t *testing.T) {
ts := runTestServer()
defer ts.Close()
2023-09-14 08:10:33 +02:00
defer shared.CloseDb()
2023-09-13 21:54:43 +02:00
t.Run("it should return 400 when JSON payload is invalid", func(t *testing.T) {
payload := []byte(`{"InvalidPayload": `)
resp, err := http.Post(fmt.Sprintf("%s/device_info", ts.URL), "application/json", bytes.NewBuffer(payload))
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
assert.Equal(t, 400, resp.StatusCode)
})
t.Run("it should log a message when IMEI is not found", func(t *testing.T) {
// Add a valid payload but with an unknown IMEI
payload := []byte(`{"IMEI": "UNKNOWN", "SomeOtherField": "Value"}`)
resp, err := http.Post(fmt.Sprintf("%s/device_info", ts.URL), "application/json", bytes.NewBuffer(payload))
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
assert.Equal(t, 200, resp.StatusCode)
})
t.Run("it should return 200 when all conditions are correct", func(t *testing.T) {
// Add a valid payload
deviceInfo := map[string]interface{}{
2023-09-18 12:27:40 +02:00
"IMEI": "SOME_VALID_IMEI",
2023-09-13 21:54:43 +02:00
"SomeOtherField": "Value",
}
payload, _ := json.Marshal(deviceInfo)
resp, err := http.Post(fmt.Sprintf("%s/device_info", ts.URL), "application/json", bytes.NewBuffer(payload))
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
assert.Equal(t, 200, resp.StatusCode)
})
}