Skip to content

Commit

Permalink
feat(server): implemented ai generated tests to learn upon
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniloMurer committed Nov 19, 2024
1 parent c1c55fb commit 6f5fb4d
Show file tree
Hide file tree
Showing 12 changed files with 708 additions and 194 deletions.
1 change: 1 addition & 0 deletions .run/test_server.run.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<working_directory value="$PROJECT_DIR$/server" />
<go_parameters value="-i" />
<kind value="DIRECTORY" />
<package value="server" />
<directory value="$PROJECT_DIR$/server" />
<filePath value="$PROJECT_DIR$" />
<framework value="gotest" />
Expand Down
14 changes: 12 additions & 2 deletions server/cmd/triffgonix/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import (
"github.com/gin-gonic/gin"
)

func main() {
// sets up the router
func setupRouter() *gin.Engine {
database.AutoMigrate()

router := gin.Default()
Expand All @@ -20,7 +21,11 @@ func main() {

router.Use(cors.New(corsConfig))

group := router.Group("/group")
router.GET("/", func(c *gin.Context) {
c.String(200, "Welcome")
})

group := router.Group("/api")
{
group.POST("/user", api.CreatePlayer)
group.GET("/user", api.GetPlayers)
Expand All @@ -33,6 +38,11 @@ func main() {
socketGroup.GET("/dart", api.HandleGeneralWebsocket)
}

return router
}

func main() {
router := setupRouter()
err := router.Run("0.0.0.0:8080")
if err != nil {
panic("Error while starting server")
Expand Down
62 changes: 62 additions & 0 deletions server/cmd/triffgonix/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package main

import (
"net/http/httptest"
"testing"

"github.com/stretchr/testify/assert"
)

func TestMain_RootRoute(t *testing.T) {
router := setupRouter()
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/", nil)
router.ServeHTTP(w, req)

assert.Equal(t, 200, w.Code)
assert.Contains(t, w.Body.String(), "Welcome")
}

func TestMain_GroupRoutes(t *testing.T) {
router := setupRouter()

tests := []struct {
method string
endpoint string
expected int
}{
{"POST", "/api/user", 400}, // Assuming it requires a body and proper setup
{"GET", "/api/user", 302},
{"POST", "/api/game", 400}, // Assuming it requires a body and proper setup
{"GET", "/api/game", 302},
}

for _, tt := range tests {
w := httptest.NewRecorder()
req := httptest.NewRequest(tt.method, tt.endpoint, nil)
router.ServeHTTP(w, req)

assert.Equal(t, tt.expected, w.Code)
}
}

func TestMain_WebSocketRoutes(t *testing.T) {
router := setupRouter()

tests := []struct {
method string
endpoint string
expected int
}{
{"GET", "/ws/dart/123", 400}, // Assuming it requires a proper WebSocket setup
{"GET", "/ws/dart", 400}, // Assuming it requires a proper WebSocket setup
}

for _, tt := range tests {
w := httptest.NewRecorder()
req := httptest.NewRequest(tt.method, tt.endpoint, nil)
router.ServeHTTP(w, req)

assert.Equal(t, tt.expected, w.Code)
}
}
380 changes: 191 additions & 189 deletions server/cover.out

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions server/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ require gorm.io/gorm v1.25.11

require (
github.com/gorilla/websocket v1.5.3
github.com/stretchr/testify v1.9.0
gorm.io/driver/sqlite v1.5.6
)

Expand All @@ -18,12 +19,14 @@ require (
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
Expand All @@ -35,6 +38,7 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.8.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions server/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MG
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
Expand Down
42 changes: 42 additions & 0 deletions server/internal/triffgonix/api/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package api

import (
"github.com/google/uuid"
"net/http/httptest"
"server/internal/triffgonix/database"
"server/internal/triffgonix/models"
"testing"

"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)

func TestCreatePlayer(t *testing.T) {
router := setupRouter()
w := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/api/user", nil)
router.ServeHTTP(w, req)

assert.Equal(t, 400, w.Code)
}

func setupRouter() *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.Default()
group := r.Group("/api")
{
group.POST("/user", CreatePlayer)
group.GET("/user", GetPlayers)
group.POST("/game", CreateGame)
group.GET("/game", GetGames)
}
return r
}

func TestDatabaseConnections(t *testing.T) {
database.AutoMigrate()
err, _ := database.CreatePlayer(&models.Player{PlayerName: uuid.Must(uuid.NewRandom()).String()})
assert.Nil(t, err)
games := database.FindAllGames()
assert.NotNil(t, games)
}
13 changes: 10 additions & 3 deletions server/internal/triffgonix/api/socket/hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,16 @@ import (

var logger = logging.NewLogger()

// WebSocketConnection defines the behavior required for a WebSocket connection
type WebSocketConnection interface {
WriteJSON(v interface{}) error
ReadJSON(v interface{}) error
Close() error
}

type Client struct {
Id string
Connection *websocket.Conn
Connection WebSocketConnection
}

type Hub struct {
Expand All @@ -21,7 +28,7 @@ type Hub struct {
}

// RegisterNewClient adds a web socket connection to the hub
func (hub *Hub) RegisterNewClient(conn *websocket.Conn) {
func (hub *Hub) RegisterNewClient(conn WebSocketConnection) {
logger.Trace("new client connected")
client := &Client{Id: "test", Connection: conn}
hub.Clients[client] = true
Expand Down Expand Up @@ -92,7 +99,7 @@ func (hub *Hub) HandleConnection(conn *websocket.Conn) {
}

// cleanupClient removes connection from the hub after disconnect
func (hub *Hub) cleanupClient(conn *websocket.Conn) {
func (hub *Hub) cleanupClient(conn WebSocketConnection) {
for client := range hub.Clients {
if client.Connection == conn {
delete(hub.Clients, client)
Expand Down
71 changes: 71 additions & 0 deletions server/internal/triffgonix/api/socket/hub_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package socket

import (
"server/pkg/logging"
"testing"
)

// Mock WebSocket connection
type MockConn struct {
WriteJSONFunc func(v interface{}) error
ReadJSONFunc func(v interface{}) error
CloseFunc func() error
}

func (m *MockConn) WriteJSON(v interface{}) error {
return m.WriteJSONFunc(v)
}

func (m *MockConn) ReadJSON(v interface{}) error {
return m.ReadJSONFunc(v)
}

func (m *MockConn) Close() error {
return m.CloseFunc()
}

func TestRegisterNewClient(t *testing.T) {
hub := &Hub{Clients: make(map[*Client]bool)}
mockConn := &MockConn{}
logger = logging.NewLogger() // Ensure logger is initialized

hub.RegisterNewClient(mockConn)

if len(hub.Clients) != 1 {
t.Errorf("expected 1 client in hub, got: %d", len(hub.Clients))
}
}

func TestBroadcastMessage(t *testing.T) {
hub := &Hub{Clients: make(map[*Client]bool)}
mockConn := &MockConn{
WriteJSONFunc: func(v interface{}) error {
return nil
},
}
client := &Client{Connection: mockConn}
hub.Clients[client] = true
logger = logging.NewLogger() // Ensure logger is initialized

message := OutgoingMessage{Type: GameState, Content: "test content"}
hub.broadcastMessage(message)
// No assertion needed. If WriteJSON panics, the test will fail
}

func TestCleanupClient(t *testing.T) {
hub := &Hub{Clients: make(map[*Client]bool)}
mockConn := &MockConn{}
client := &Client{Connection: mockConn}
hub.Clients[client] = true
logger = logging.NewLogger() // Ensure logger is initialized

if len(hub.Clients) != 1 {
t.Errorf("expected 1 client, got: %d", len(hub.Clients))
}

hub.cleanupClient(mockConn)

if len(hub.Clients) != 0 {
t.Errorf("expected 0 clients after cleanup, got: %d", len(hub.Clients))
}
}
Loading

0 comments on commit 6f5fb4d

Please sign in to comment.