github.com/simpleiot/simpleiot@v0.18.3/server/test-server.go (about) 1 package server 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "os/exec" 8 "time" 9 10 "github.com/nats-io/nats.go" 11 "github.com/simpleiot/simpleiot/client" 12 "github.com/simpleiot/simpleiot/data" 13 ) 14 15 // TestServerOptions options used for test server 16 var TestServerOptions = Options{ 17 StoreFile: "test.sqlite", 18 NatsPort: 8900, 19 HTTPPort: "8901", 20 NatsHTTPPort: 8902, 21 NatsWSPort: 8903, 22 NatsServer: "nats://localhost:8900", 23 ID: "inst1", 24 } 25 26 // TestServerOptions2 options used for 2nd test server 27 var TestServerOptions2 = Options{ 28 StoreFile: "test2.sqlite", 29 NatsPort: 8910, 30 HTTPPort: "8911", 31 NatsHTTPPort: 8912, 32 NatsWSPort: 8913, 33 NatsServer: "nats://localhost:8910", 34 ID: "inst2", 35 } 36 37 // TestServer starts a test server and returns a function to stop it 38 func TestServer(args ...string) (*nats.Conn, data.NodeEdge, func(), error) { 39 opts := TestServerOptions 40 41 if len(args) > 0 { 42 opts = TestServerOptions2 43 } 44 45 cleanup := func() { 46 _ = exec.Command("sh", "-c", 47 fmt.Sprintf("rm %v*", opts.StoreFile)).Run() 48 } 49 50 cleanup() 51 52 s, nc, err := NewServer(opts) 53 54 if err != nil { 55 return nil, data.NodeEdge{}, nil, fmt.Errorf("Error starting siot server: %v", err) 56 } 57 58 clients, _ := client.DefaultClients(nc) 59 s.AddClient(clients) 60 61 stopped := make(chan struct{}) 62 63 go func() { 64 err := s.Run() 65 if err != nil { 66 log.Println("Test Server start returned:", err) 67 } 68 close(stopped) 69 }() 70 71 stop := func() { 72 s.Stop(nil) 73 <-stopped 74 cleanup() 75 } 76 77 ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) 78 err = s.WaitStart(ctx) 79 cancel() 80 if err != nil { 81 return nil, data.NodeEdge{}, stop, fmt.Errorf("Error waiting for test server to start: %v", err) 82 } 83 84 nodes, err := client.GetNodes(nc, "root", "all", "", false) 85 86 if err != nil { 87 return nil, data.NodeEdge{}, stop, fmt.Errorf("Get root nodes error: %v", err) 88 } 89 90 if len(nodes) < 1 { 91 return nil, data.NodeEdge{}, stop, fmt.Errorf("Did not get a root node") 92 } 93 94 return nc, nodes[0], stop, nil 95 }