Fix test instabilities by refactoring to make address dynamic and readable

This commit is contained in:
Marc Di Luzio 2020-06-06 11:52:12 +01:00
parent bc366583a4
commit 1d2087e2b9
7 changed files with 82 additions and 31 deletions

View file

@ -1,6 +1,7 @@
package main
import (
"fmt"
"os"
"testing"
@ -10,16 +11,27 @@ import (
"github.com/stretchr/testify/assert"
)
var serv rove.Server = "localhost:8080"
// To be set by the main function
var serv rove.Server
func TestMain(m *testing.M) {
s := server.NewServer(server.OptionPort(8080))
s.Initialise()
s := server.NewServer()
if err := s.Initialise(); 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()
s.Close()
if err := s.Close(); err != nil {
fmt.Println(err)
os.Exit(1)
}
os.Exit(code)
}

View file

@ -6,6 +6,7 @@ import (
"os"
"os/signal"
"syscall"
"time"
"github.com/mdiluz/rove/pkg/persistence"
"github.com/mdiluz/rove/pkg/server"
@ -13,8 +14,9 @@ import (
)
var ver = flag.Bool("version", false, "Display version number")
var port = flag.Int("port", 8080, "The port to host on")
var port = flag.String("address", ":8080", "The address to host on")
var data = flag.String("data", os.TempDir(), "Directory to store persistant data")
var quit = flag.Int("quit", 0, "Quit after n seconds, useful for testing")
func main() {
flag.Parse()
@ -32,7 +34,7 @@ func main() {
// Create the server data
s := server.NewServer(
server.OptionPort(*port),
server.OptionAddress(*port),
server.OptionPersistentData())
// Initialise the server
@ -52,9 +54,19 @@ func main() {
os.Exit(0)
}()
fmt.Println("Running...")
// Quit after a time if requested
if *quit != 0 {
go func() {
time.Sleep(time.Duration(*quit) * time.Second)
if err := s.Close(); err != nil {
panic(err)
}
os.Exit(0)
}()
}
// Run the server
fmt.Printf("Serving HTTP on %s\n", s.Addr())
s.Run()
// Close the server

View file

@ -2,6 +2,7 @@ package main
import (
"flag"
"fmt"
"os"
"path"
"testing"
@ -11,14 +12,26 @@ import (
"github.com/stretchr/testify/assert"
)
var address string
func TestMain(m *testing.M) {
s := server.NewServer(server.OptionPort(8080))
s.Initialise()
s := server.NewServer()
if err := s.Initialise(); err != nil {
fmt.Println(err)
os.Exit(1)
}
address = s.Addr()
go s.Run()
fmt.Printf("Test server hosted on %s", address)
code := m.Run()
s.Close()
if err := s.Close(); err != nil {
fmt.Println(err)
os.Exit(1)
}
os.Exit(code)
}
@ -31,7 +44,7 @@ func Test_InnerMain(t *testing.T) {
assert.Error(t, InnerMain("status"))
// Now set the host
flag.Set("host", "localhost:8080")
flag.Set("host", address)
// No error now as we have a host
assert.NoError(t, InnerMain("status"))