dont marshal uninitialized players

This commit is contained in:
Bel LaPointe
2021-03-12 07:04:38 -06:00
parent 3efa60f2d0
commit aaf4ff3161
4 changed files with 44 additions and 2 deletions

View File

@@ -8,9 +8,11 @@ import (
"strings" "strings"
) )
type Players [16]Player
type Game struct { type Game struct {
Pot Currency Pot Currency
Players [16]Player Players Players
} }
type Player struct { type Player struct {
@@ -32,6 +34,12 @@ func (game Game) GetPlayers() []Player {
return players return players
} }
func (players Players) MarshalJSON() ([]byte, error) {
game := Game{Players: players}
subplayers := game.GetPlayers()
return json.Marshal(subplayers)
}
func (p Player) Empty() bool { func (p Player) Empty() bool {
return p == (Player{}) return p == (Player{})
} }

View File

@@ -5,6 +5,36 @@ import (
"testing" "testing"
) )
func TestPlayersMarshal(t *testing.T) {
t.Run("0", func(t *testing.T) {
var ps Players
b, err := json.Marshal(ps)
if err != nil {
t.Fatal(err)
}
if s := string(b); s != "[]" {
t.Fatalf("didnt marshal empty Players as []: got %s", s)
}
})
t.Run("2", func(t *testing.T) {
var ps Players
ps[3].ID = "hi"
ps[9].ID = "hi2"
b, err := json.Marshal(ps)
if err != nil {
t.Fatal(err)
}
var ps2 []Player
if err := json.Unmarshal(b, &ps2); err != nil {
t.Fatalf("%v: %s", err, b)
}
if len(ps2) != 2 {
t.Fatal(len(ps2))
}
})
}
func TestCurrencyMarshal(t *testing.T) { func TestCurrencyMarshal(t *testing.T) {
cases := map[string]struct { cases := map[string]struct {
input Currency input Currency

View File

@@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"local/router" "local/router"
"local/storage"
"log" "log"
"net/http" "net/http"
"strings" "strings"
@@ -109,6 +110,9 @@ func badRequest(w http.ResponseWriter, message string) {
} }
func errHandler(w http.ResponseWriter, status int, message string) { func errHandler(w http.ResponseWriter, status int, message string) {
if message == storage.ErrNotFound.Error() {
status = http.StatusNotFound
}
w.WriteHeader(status) w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]interface{}{ json.NewEncoder(w).Encode(map[string]interface{}{
"status": http.StatusText(status), "status": http.StatusText(status),

View File

@@ -39,7 +39,7 @@ func TestServerRouter(t *testing.T) {
w := httptest.NewRecorder() w := httptest.NewRecorder()
r := httptest.NewRequest(c.method, c.path, strings.NewReader("{}")) r := httptest.NewRequest(c.method, c.path, strings.NewReader("{}"))
server.ServeHTTP(w, r) server.ServeHTTP(w, r)
if w.Code == http.StatusNotFound { if w.Code == http.StatusNotFound && string(w.Body.Bytes()) == "404 page not found" {
t.Fatalf("not found: (%s) %s: (%v) %s", c.method, c.path, w.Code, w.Body.Bytes()) t.Fatalf("not found: (%s) %s: (%v) %s", c.method, c.path, w.Code, w.Body.Bytes())
} }
}) })