-
Notifications
You must be signed in to change notification settings - Fork 3
/
test_server.go
133 lines (101 loc) · 2.28 KB
/
test_server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package meduza
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"time"
)
type TestServer struct {
cmd *exec.Cmd
running bool
port int
ctlPort int
}
const (
// The env var for the meduza executable. If not set, we default to running "meduzad" from PATH
MeduzaBinEnvvar = "MEDUZA_BIN"
mdzCommand = "meduzad"
launchWaitTimeout = 250 * time.Millisecond
)
// Start and run the process, return an error if it cannot be run
func (s *TestServer) run() error {
ret := s.cmd.Start()
ch := make(chan error)
// we wait for LaunchWaitTimeout and see if the server quit due to an error
go func() {
err := s.cmd.Wait()
select {
case ch <- err:
default:
}
}()
select {
case e := <-ch:
log.Println("Error waiting for process:", e)
return e
case <-time.After(launchWaitTimeout):
break
}
return ret
}
// Create and run a new server on a given port.
// Return an error if the server cannot be started
func NewTestServer(port, ctlPort int, cmdlineArgs ...string) (*TestServer, error) {
mdz := os.Getenv("MEDUZA_BIN")
if mdz == "" {
mdz = mdzCommand
}
cmdlineArgs = append(cmdlineArgs, "-test",
fmt.Sprintf("-port=%d", port), fmt.Sprintf("-ctl_port=%d", ctlPort))
cmd := exec.Command(mdz, cmdlineArgs...)
log.Println("start args: ", cmd.Args)
s := &TestServer{
cmd: cmd,
running: false,
port: port,
ctlPort: ctlPort,
}
err := s.run()
if err != nil {
return nil, err
}
s.running = true
return s, nil
}
func (s *TestServer) Stop() error {
if !s.running {
return nil
}
s.running = false
if err := s.cmd.Process.Kill(); err != nil {
return err
}
s.cmd.Wait()
return nil
}
func (s *TestServer) CtlUrl() string {
return fmt.Sprintf("http://127.0.0.1:%d", s.ctlPort)
}
func (s *TestServer) DeploySchema(r io.Reader) error {
u := fmt.Sprintf("%s/deploy", s.CtlUrl())
res, err := http.Post(u, "text/yaml", r)
if err != nil {
return fmt.Errorf("Could not post deploy request to server: %s", err)
}
defer res.Body.Close()
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("Could not read response body: %s", err)
}
rc := string(b)
if rc == "OK" {
log.Println("Schema deployed successfully")
} else {
return fmt.Errorf("Error deploying schema. Server error: %s", s)
}
return nil
}