Move server package out into rove-server

This commit is contained in:
Marc Di Luzio 2020-06-10 17:39:42 +01:00
parent 62d6213c1a
commit 6fb7ee598d
9 changed files with 27 additions and 41 deletions

View file

@ -0,0 +1,147 @@
package internal
import (
"fmt"
"os"
"testing"
"github.com/google/uuid"
"github.com/mdiluz/rove/pkg/game"
"github.com/mdiluz/rove/pkg/rove"
"github.com/stretchr/testify/assert"
)
// To be set by the main function
var serv rove.Server
func TestMain(m *testing.M) {
s := NewServer()
if err := s.Initialise(true); err != nil {
fmt.Println(err)
os.Exit(1)
}
serv = rove.Server(s.Addr())
go s.Run()
fmt.Printf("Test server hosted on %s", serv)
code := m.Run()
if err := s.StopAndClose(); err != nil {
fmt.Println(err)
os.Exit(1)
}
os.Exit(code)
}
func TestServer_Status(t *testing.T) {
status, err := serv.Status()
assert.NoError(t, err)
assert.True(t, status.Ready)
assert.NotZero(t, len(status.Version))
}
func TestServer_Register(t *testing.T) {
d1 := rove.RegisterData{
Name: uuid.New().String(),
}
r1, err := serv.Register(d1)
assert.NoError(t, err)
assert.True(t, r1.Success)
assert.NotZero(t, len(r1.Id))
d2 := rove.RegisterData{
Name: uuid.New().String(),
}
r2, err := serv.Register(d2)
assert.NoError(t, err)
assert.True(t, r2.Success)
assert.NotZero(t, len(r2.Id))
r3, err := serv.Register(d1)
assert.NoError(t, err)
assert.False(t, r3.Success)
}
func TestServer_Spawn(t *testing.T) {
d1 := rove.RegisterData{
Name: uuid.New().String(),
}
r1, err := serv.Register(d1)
assert.NoError(t, err)
assert.True(t, r1.Success)
assert.NotZero(t, len(r1.Id))
s := rove.SpawnData{}
r2, err := serv.Spawn(r1.Id, s)
assert.NoError(t, err)
assert.True(t, r2.Success)
}
func TestServer_Command(t *testing.T) {
d1 := rove.RegisterData{
Name: uuid.New().String(),
}
r1, err := serv.Register(d1)
assert.NoError(t, err)
assert.True(t, r1.Success)
assert.NotZero(t, len(r1.Id))
s := rove.SpawnData{}
r2, err := serv.Spawn(r1.Id, s)
assert.NoError(t, err)
assert.True(t, r2.Success)
c := rove.CommandData{
Commands: []game.Command{
{
Command: game.CommandMove,
Bearing: "N",
Duration: 1,
},
},
}
r3, err := serv.Command(r1.Id, c)
assert.NoError(t, err)
assert.True(t, r3.Success)
}
func TestServer_Radar(t *testing.T) {
d1 := rove.RegisterData{
Name: uuid.New().String(),
}
r1, err := serv.Register(d1)
assert.NoError(t, err)
assert.True(t, r1.Success)
assert.NotZero(t, len(r1.Id))
s := rove.SpawnData{}
r2, err := serv.Spawn(r1.Id, s)
assert.NoError(t, err)
assert.True(t, r2.Success)
r3, err := serv.Radar(r1.Id)
assert.NoError(t, err)
assert.True(t, r3.Success)
}
func TestServer_Rover(t *testing.T) {
d1 := rove.RegisterData{
Name: uuid.New().String(),
}
r1, err := serv.Register(d1)
assert.NoError(t, err)
assert.True(t, r1.Success)
assert.NotZero(t, len(r1.Id))
s := rove.SpawnData{}
r2, err := serv.Spawn(r1.Id, s)
assert.NoError(t, err)
assert.True(t, r2.Success)
r3, err := serv.Rover(r1.Id)
assert.NoError(t, err)
assert.True(t, r3.Success)
}

View file

@ -0,0 +1,235 @@
package internal
import (
"encoding/json"
"fmt"
"io"
"net/http"
"github.com/google/uuid"
"github.com/mdiluz/rove/pkg/rove"
"github.com/mdiluz/rove/pkg/version"
)
// Handler describes a function that handles any incoming request and can respond
type Handler func(*Server, map[string]string, io.ReadCloser, io.Writer) (interface{}, error)
// Route defines the information for a single path->function route
type Route struct {
path string
method string
handler Handler
}
// Routes is an array of all the Routes
var Routes = []Route{
{
path: "/status",
method: http.MethodGet,
handler: HandleStatus,
},
{
path: "/register",
method: http.MethodPost,
handler: HandleRegister,
},
{
path: "/{account}/spawn",
method: http.MethodPost,
handler: HandleSpawn,
},
{
path: "/{account}/command",
method: http.MethodPost,
handler: HandleCommand,
},
{
path: "/{account}/radar",
method: http.MethodGet,
handler: HandleRadar,
},
{
path: "/{account}/rover",
method: http.MethodGet,
handler: HandleRover,
},
}
// HandleStatus handles the /status request
func HandleStatus(s *Server, vars map[string]string, b io.ReadCloser, w io.Writer) (interface{}, error) {
// Simply return the current server status
response := rove.StatusResponse{
Ready: true,
Version: version.Version,
Tick: s.tick,
}
// If there's a schedule, respond with it
if len(s.schedule.Entries()) > 0 {
response.NextTick = s.schedule.Entries()[0].Next.Format("15:04:05")
}
return response, nil
}
// HandleRegister handles /register endpoint
func HandleRegister(s *Server, vars map[string]string, b io.ReadCloser, w io.Writer) (interface{}, error) {
var response = rove.RegisterResponse{
Success: false,
}
// Decode the registration info, verify it and register the account
var data rove.RegisterData
err := json.NewDecoder(b).Decode(&data)
if err != nil {
fmt.Printf("Failed to decode json: %s\n", err)
response.Error = err.Error()
} else if len(data.Name) == 0 {
response.Error = "Cannot register empty name"
} else if acc, err := s.accountant.RegisterAccount(data.Name); err != nil {
response.Error = err.Error()
} else if err := s.SaveAll(); err != nil {
response.Error = fmt.Sprintf("Internal server error when saving accounts: %s", err)
} else {
// Save out the new accounts
response.Id = acc.Id.String()
response.Success = true
}
fmt.Printf("register response:%+v\n", response)
return response, nil
}
// HandleSpawn will spawn the player entity for the associated account
func HandleSpawn(s *Server, vars map[string]string, b io.ReadCloser, w io.Writer) (interface{}, error) {
var response = rove.SpawnResponse{
Success: false,
}
id := vars["account"]
// Decode the spawn info, verify it and spawn the rover for this account
var data rove.SpawnData
if err := json.NewDecoder(b).Decode(&data); err != nil {
fmt.Printf("Failed to decode json: %s\n", err)
response.Error = err.Error()
} else if len(id) == 0 {
response.Error = "No account ID provided"
} else if id, err := uuid.Parse(id); err != nil {
response.Error = "Provided account ID was invalid"
} else if attribs, _, err := s.SpawnRoverForAccount(id); err != nil {
response.Error = err.Error()
} else if err := s.SaveWorld(); err != nil {
response.Error = fmt.Sprintf("Internal server error when saving world: %s", err)
} else {
response.Success = true
response.Attributes = attribs
}
fmt.Printf("spawn response \taccount:%s\tresponse:%+v\n", id, response)
return response, nil
}
// HandleSpawn will spawn the player entity for the associated account
func HandleCommand(s *Server, vars map[string]string, b io.ReadCloser, w io.Writer) (interface{}, error) {
var response = rove.CommandResponse{
Success: false,
}
id := vars["account"]
// Decode the commands, verify them and the account, and execute the commands
var data rove.CommandData
if err := json.NewDecoder(b).Decode(&data); err != nil {
fmt.Printf("Failed to decode json: %s\n", err)
response.Error = err.Error()
} else if len(id) == 0 {
response.Error = "No account ID provided"
} else if id, err := uuid.Parse(id); err != nil {
response.Error = fmt.Sprintf("Provided account ID was invalid: %s", err)
} else if inst, err := s.accountant.GetRover(id); err != nil {
response.Error = fmt.Sprintf("Provided account has no rover: %s", err)
} else if err := s.world.Enqueue(inst, data.Commands...); err != nil {
response.Error = fmt.Sprintf("Failed to execute commands: %s", err)
} else {
response.Success = true
}
fmt.Printf("command response \taccount:%s\tresponse:%+v\n", id, response)
return response, nil
}
// HandleRadar handles the radar request
func HandleRadar(s *Server, vars map[string]string, b io.ReadCloser, w io.Writer) (interface{}, error) {
var response = rove.RadarResponse{
Success: false,
}
id := vars["account"]
if len(id) == 0 {
response.Error = "No account ID provided"
} else if id, err := uuid.Parse(id); err != nil {
response.Error = fmt.Sprintf("Provided account ID was invalid: %s", err)
} else if inst, err := s.accountant.GetRover(id); err != nil {
response.Error = fmt.Sprintf("Provided account has no rover: %s", err)
} else if attrib, err := s.world.RoverAttributes(inst); err != nil {
response.Error = fmt.Sprintf("Error getting rover attributes: %s", err)
} else if radar, err := s.world.RadarFromRover(inst); err != nil {
response.Error = fmt.Sprintf("Error getting radar from rover: %s", err)
} else {
response.Tiles = radar
response.Range = attrib.Range
response.Success = true
}
fmt.Printf("radar response \taccount:%s\tresponse:%+v\n", id, response)
return response, nil
}
// HandleRover handles the rover request
func HandleRover(s *Server, vars map[string]string, b io.ReadCloser, w io.Writer) (interface{}, error) {
var response = rove.RoverResponse{
Success: false,
}
id := vars["account"]
if len(id) == 0 {
response.Error = "No account ID provided"
} else if id, err := uuid.Parse(id); err != nil {
response.Error = fmt.Sprintf("Provided account ID was invalid: %s", err)
} else if inst, err := s.accountant.GetRover(id); err != nil {
response.Error = fmt.Sprintf("Provided account has no rover: %s", err)
} else if attribs, err := s.world.RoverAttributes(inst); err != nil {
response.Error = fmt.Sprintf("Error getting radar from rover: %s", err)
} else {
response.Attributes = attribs
response.Success = true
}
fmt.Printf("rover response \taccount:%s\tresponse:%+v\n", id, response)
return response, nil
}

View file

@ -0,0 +1,217 @@
package internal
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"path"
"testing"
"github.com/mdiluz/rove/pkg/game"
"github.com/mdiluz/rove/pkg/rove"
"github.com/mdiluz/rove/pkg/vector"
"github.com/stretchr/testify/assert"
)
func TestHandleStatus(t *testing.T) {
request, _ := http.NewRequest(http.MethodGet, "/status", nil)
response := httptest.NewRecorder()
s := NewServer()
s.Initialise(true)
s.router.ServeHTTP(response, request)
assert.Equal(t, http.StatusOK, response.Code)
var status rove.StatusResponse
json.NewDecoder(response.Body).Decode(&status)
if status.Ready != true {
t.Errorf("got false for /status")
}
if len(status.Version) == 0 {
t.Errorf("got empty version info")
}
}
func TestHandleRegister(t *testing.T) {
data := rove.RegisterData{Name: "one"}
b, err := json.Marshal(data)
if err != nil {
t.Error(err)
}
request, _ := http.NewRequest(http.MethodPost, "/register", bytes.NewReader(b))
response := httptest.NewRecorder()
s := NewServer()
s.Initialise(true)
s.router.ServeHTTP(response, request)
assert.Equal(t, http.StatusOK, response.Code)
var status rove.RegisterResponse
json.NewDecoder(response.Body).Decode(&status)
if status.Success != true {
t.Errorf("got false for /register")
}
}
func TestHandleSpawn(t *testing.T) {
s := NewServer()
s.Initialise(true)
a, err := s.accountant.RegisterAccount("test")
assert.NoError(t, err, "Error registering account")
data := rove.SpawnData{}
b, err := json.Marshal(data)
assert.NoError(t, err, "Error marshalling data")
request, _ := http.NewRequest(http.MethodPost, path.Join("/", a.Id.String(), "/spawn"), bytes.NewReader(b))
response := httptest.NewRecorder()
s.router.ServeHTTP(response, request)
assert.Equal(t, http.StatusOK, response.Code)
var status rove.SpawnResponse
json.NewDecoder(response.Body).Decode(&status)
assert.Equal(t, http.StatusOK, response.Code)
if status.Success != true {
t.Errorf("got false for /spawn: %s", status.Error)
}
}
func TestHandleCommand(t *testing.T) {
s := NewServer()
s.Initialise(false) // Leave the world empty with no obstacles
a, err := s.accountant.RegisterAccount("test")
assert.NoError(t, err, "Error registering account")
// Spawn the rover rover for the account
_, inst, err := s.SpawnRoverForAccount(a.Id)
assert.NoError(t, s.world.WarpRover(inst, vector.Vector{}))
attribs, err := s.world.RoverAttributes(inst)
assert.NoError(t, err, "Couldn't get rover position")
data := rove.CommandData{
Commands: []game.Command{
{
Command: game.CommandMove,
Bearing: "N",
Duration: 1,
},
},
}
b, err := json.Marshal(data)
assert.NoError(t, err, "Error marshalling data")
request, _ := http.NewRequest(http.MethodPost, path.Join("/", a.Id.String(), "/command"), bytes.NewReader(b))
response := httptest.NewRecorder()
s.router.ServeHTTP(response, request)
assert.Equal(t, http.StatusOK, response.Code)
var status rove.CommandResponse
json.NewDecoder(response.Body).Decode(&status)
if status.Success != true {
t.Errorf("got false for /command: %s", status.Error)
}
attrib, err := s.world.RoverAttributes(inst)
assert.NoError(t, err, "Couldn't get rover attribs")
// Tick the command queues to progress the move command
s.world.EnqueueAllIncoming()
s.world.ExecuteCommandQueues()
attribs2, err := s.world.RoverAttributes(inst)
assert.NoError(t, err, "Couldn't get rover position")
attribs.Pos.Add(vector.Vector{X: 0.0, Y: attrib.Speed * 1}) // Should have moved north by the speed and duration
assert.Equal(t, attribs.Pos, attribs2.Pos, "Rover should have moved by bearing")
}
func TestHandleRadar(t *testing.T) {
s := NewServer()
s.Initialise(false) // Spawn a clean world
a, err := s.accountant.RegisterAccount("test")
assert.NoError(t, err, "Error registering account")
// Spawn the rover rover for the account
attrib, id, err := s.SpawnRoverForAccount(a.Id)
assert.NoError(t, err)
// Warp this rover to 0,0
assert.NoError(t, s.world.WarpRover(id, vector.Vector{}))
// Explicity set a few nearby tiles
wallPos1 := vector.Vector{X: 0, Y: -1}
wallPos2 := vector.Vector{X: 1, Y: 1}
rockPos := vector.Vector{X: 1, Y: 3}
emptyPos := vector.Vector{X: -2, Y: -3}
assert.NoError(t, s.world.Atlas.SetTile(wallPos1, game.TileWall))
assert.NoError(t, s.world.Atlas.SetTile(wallPos2, game.TileWall))
assert.NoError(t, s.world.Atlas.SetTile(rockPos, game.TileRock))
assert.NoError(t, s.world.Atlas.SetTile(emptyPos, game.TileEmpty))
request, _ := http.NewRequest(http.MethodGet, path.Join("/", a.Id.String(), "/radar"), nil)
response := httptest.NewRecorder()
s.router.ServeHTTP(response, request)
assert.Equal(t, http.StatusOK, response.Code)
var status rove.RadarResponse
json.NewDecoder(response.Body).Decode(&status)
if status.Success != true {
t.Errorf("got false for /radar: %s", status.Error)
}
scope := attrib.Range*2 + 1
radarOrigin := vector.Vector{X: -attrib.Range, Y: -attrib.Range}
// Make sure the rover tile is correct
assert.Equal(t, game.TileRover, status.Tiles[len(status.Tiles)/2])
// Check our other tiles
wallPos1.Add(radarOrigin.Negated())
wallPos2.Add(radarOrigin.Negated())
rockPos.Add(radarOrigin.Negated())
emptyPos.Add(radarOrigin.Negated())
assert.Equal(t, game.TileWall, status.Tiles[wallPos1.X+wallPos1.Y*scope])
assert.Equal(t, game.TileWall, status.Tiles[wallPos2.X+wallPos2.Y*scope])
assert.Equal(t, game.TileRock, status.Tiles[rockPos.X+rockPos.Y*scope])
assert.Equal(t, game.TileEmpty, status.Tiles[emptyPos.X+emptyPos.Y*scope])
}
func TestHandleRover(t *testing.T) {
s := NewServer()
s.Initialise(true)
a, err := s.accountant.RegisterAccount("test")
assert.NoError(t, err, "Error registering account")
// Spawn one rover for the account
attribs, _, err := s.SpawnRoverForAccount(a.Id)
assert.NoError(t, err)
request, _ := http.NewRequest(http.MethodGet, path.Join("/", a.Id.String(), "/rover"), nil)
response := httptest.NewRecorder()
s.router.ServeHTTP(response, request)
assert.Equal(t, http.StatusOK, response.Code)
var status rove.RoverResponse
json.NewDecoder(response.Body).Decode(&status)
if status.Success != true {
t.Errorf("got false for /rover: %s", status.Error)
} else if attribs != status.Attributes {
t.Errorf("Missmatched attributes: %+v, !=%+v", attribs, status.Attributes)
}
}

View file

@ -0,0 +1,303 @@
package internal
import (
"context"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"sync"
"time"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/mdiluz/rove/pkg/accounts"
"github.com/mdiluz/rove/pkg/game"
"github.com/mdiluz/rove/pkg/persistence"
"github.com/robfig/cron"
)
const (
// PersistentData will allow the server to load and save it's state
PersistentData = iota
// EphemeralData will let the server neither load or save out any of it's data
EphemeralData
)
// Server contains the relevant data to run a game server
type Server struct {
// Internal state
accountant *accounts.Accountant
world *game.World
// HTTP server
listener net.Listener
server *http.Server
router *mux.Router
// Config settings
address string
persistence int
tick int
// sync point for sub-threads
sync sync.WaitGroup
// cron schedule for world ticks
schedule *cron.Cron
}
// ServerOption defines a server creation option
type ServerOption func(s *Server)
// OptionAddress sets the server address for hosting
func OptionAddress(address string) ServerOption {
return func(s *Server) {
s.address = address
}
}
// OptionPersistentData sets the server data to be persistent
func OptionPersistentData() ServerOption {
return func(s *Server) {
s.persistence = PersistentData
}
}
// OptionTick defines the number of minutes per tick
// 0 means no automatic server tick
func OptionTick(minutes int) ServerOption {
return func(s *Server) {
s.tick = minutes
}
}
// NewServer sets up a new server
func NewServer(opts ...ServerOption) *Server {
router := mux.NewRouter().StrictSlash(true)
// Set up the default server
s := &Server{
address: "",
persistence: EphemeralData,
router: router,
schedule: cron.New(),
}
// Apply all options
for _, o := range opts {
o(s)
}
// Set up the server object
s.server = &http.Server{Addr: s.address, Handler: s.router}
// Create the accountant
s.accountant = accounts.NewAccountant()
// Start small, we can grow the world later
s.world = game.NewWorld(4, 8)
return s
}
// Initialise sets up internal state ready to serve
func (s *Server) Initialise(fillWorld bool) (err error) {
// Add to our sync
s.sync.Add(1)
// Spawn a border on the default world
if err := s.world.SpawnWorld(fillWorld); err != nil {
return err
}
// Load the accounts if requested
if err := s.LoadAll(); err != nil {
return err
}
// Set up the handlers
for _, route := range Routes {
s.router.HandleFunc(route.path, s.wrapHandler(route.method, route.handler))
}
// Start the listen
if s.listener, err = net.Listen("tcp", s.server.Addr); err != nil {
return err
}
s.address = s.listener.Addr().String()
return nil
}
// Addr will return the server address set after the listen
func (s *Server) Addr() string {
return s.address
}
// Run executes the server
func (s *Server) Run() {
defer s.sync.Done()
// Set up the schedule if requested
if s.tick != 0 {
if err := s.schedule.AddFunc(fmt.Sprintf("0 */%d * * *", s.tick), func() {
// Ensure we don't quit during this function
s.sync.Add(1)
defer s.sync.Done()
fmt.Println("Executing server tick")
// Run the command queues
s.world.ExecuteCommandQueues()
// Save out the new world state
s.SaveWorld()
}); err != nil {
log.Fatal(err)
}
s.schedule.Start()
fmt.Printf("First server tick scheduled for %s\n", s.schedule.Entries()[0].Next.Format("15:04:05"))
}
// Serve the http requests
if err := s.server.Serve(s.listener); err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
}
// Stop will stop the current server
func (s *Server) Stop() error {
// Stop the cron
s.schedule.Stop()
// Try and shut down the http server
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.server.Shutdown(ctx); err != nil {
return err
}
return nil
}
// Close waits until the server is finished and closes up shop
func (s *Server) Close() error {
// Wait until the server has shut down
s.sync.Wait()
// Save and return
return s.SaveAll()
}
// Close waits until the server is finished and closes up shop
func (s *Server) StopAndClose() error {
// Stop the server
if err := s.Stop(); err != nil {
return err
}
// Close and return
return s.Close()
}
// SaveWorld will save out the world file
func (s *Server) SaveWorld() error {
if s.persistence == PersistentData {
s.world.RLock()
defer s.world.RUnlock()
if err := persistence.SaveAll("world", s.world); err != nil {
return fmt.Errorf("failed to save out persistent data: %s", err)
}
}
return nil
}
// SaveAccounts will save out the accounts file
func (s *Server) SaveAccounts() error {
if s.persistence == PersistentData {
if err := persistence.SaveAll("accounts", s.accountant); err != nil {
return fmt.Errorf("failed to save out persistent data: %s", err)
}
}
return nil
}
// SaveAll will save out all server files
func (s *Server) SaveAll() error {
// Save the accounts if requested
if s.persistence == PersistentData {
s.world.RLock()
defer s.world.RUnlock()
if err := persistence.SaveAll("accounts", s.accountant, "world", s.world); err != nil {
return err
}
}
return nil
}
// LoadAll will load all persistent data
func (s *Server) LoadAll() error {
if s.persistence == PersistentData {
s.world.Lock()
defer s.world.Unlock()
if err := persistence.LoadAll("accounts", &s.accountant, "world", &s.world); err != nil {
return err
}
}
return nil
}
// wrapHandler wraps a request handler in http checks
func (s *Server) wrapHandler(method string, handler Handler) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
// Log the request
fmt.Printf("%s\t%s\n", r.Method, r.RequestURI)
vars := mux.Vars(r)
// Verify the method, call the handler, and encode the return
if r.Method != method {
w.WriteHeader(http.StatusMethodNotAllowed)
} else if val, err := handler(s, vars, r.Body, w); err != nil {
fmt.Printf("Failed to handle http request: %s", err)
w.WriteHeader(http.StatusInternalServerError)
} else if err := json.NewEncoder(w).Encode(val); err != nil {
fmt.Printf("Failed to encode reply to json: %s", err)
w.WriteHeader(http.StatusInternalServerError)
} else {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
}
}
}
// SpawnRoverForAccount spawns the rover rover for an account
func (s *Server) SpawnRoverForAccount(accountid uuid.UUID) (game.RoverAttributes, uuid.UUID, error) {
if inst, err := s.world.SpawnRover(); err != nil {
return game.RoverAttributes{}, uuid.UUID{}, err
} else if attribs, err := s.world.RoverAttributes(inst); err != nil {
return game.RoverAttributes{}, uuid.UUID{}, fmt.Errorf("No attributes found for created rover: %s", err)
} else {
if err := s.accountant.AssignRover(accountid, inst); err != nil {
// Try and clear up the rover
if err := s.world.DestroyRover(inst); err != nil {
fmt.Printf("Failed to destroy rover after failed rover assign: %s", err)
}
return game.RoverAttributes{}, uuid.UUID{}, err
} else {
return attribs, inst, nil
}
}
}

View file

@ -0,0 +1,60 @@
package internal
import (
"testing"
)
func TestNewServer(t *testing.T) {
server := NewServer()
if server == nil {
t.Error("Failed to create server")
}
}
func TestNewServer_OptionAddress(t *testing.T) {
server := NewServer(OptionAddress(":1234"))
if server == nil {
t.Error("Failed to create server")
} else if server.address != ":1234" {
t.Error("Failed to set server address")
}
}
func TestNewServer_OptionPersistentData(t *testing.T) {
server := NewServer(OptionPersistentData())
if server == nil {
t.Error("Failed to create server")
} else if server.persistence != PersistentData {
t.Error("Failed to set server persistent data")
}
}
func TestServer_Run(t *testing.T) {
server := NewServer()
if server == nil {
t.Error("Failed to create server")
} else if err := server.Initialise(true); err != nil {
t.Error(err)
}
go server.Run()
if err := server.StopAndClose(); err != nil {
t.Error(err)
}
}
func TestServer_RunPersistentData(t *testing.T) {
server := NewServer(OptionPersistentData())
if server == nil {
t.Error("Failed to create server")
} else if err := server.Initialise(true); err != nil {
t.Error(err)
}
go server.Run()
if err := server.StopAndClose(); err != nil {
t.Error(err)
}
}