Skip to content

Commit a76f116

Browse files
authored
add Test case for using ctrl c to stop engine (#286)
* add Test case for using ctrl c to stop * No need waiting for waitingPortConnectionRefused
1 parent 190d721 commit a76f116

File tree

1 file changed

+49
-9
lines changed

1 file changed

+49
-9
lines changed

runner/engine_test.go

+49-9
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
package runner
22

33
import (
4+
"errors"
45
"fmt"
56
"net"
67
"os"
8+
"os/signal"
79
"strings"
10+
"syscall"
811
"testing"
912
"time"
1013

@@ -152,8 +155,7 @@ func TestRebuild(t *testing.T) {
152155
if err != nil {
153156
t.Fatalf("Should not be fail: %s.", err)
154157
}
155-
time.Sleep(2 * time.Second)
156-
err = waitingPortConnectionRefused(port, time.Second*5)
158+
err = waitingPortConnectionRefused(port, time.Second*10)
157159
if err != nil {
158160
t.Fatalf("timeout: %s.", err)
159161
}
@@ -171,24 +173,62 @@ func TestRebuild(t *testing.T) {
171173

172174
func waitingPortConnectionRefused(port int, timeout time.Duration) error {
173175
t := time.NewTimer(timeout)
176+
ticker := time.NewTicker(time.Millisecond * 100)
177+
defer ticker.Stop()
174178
defer t.Stop()
175179
for {
176180
select {
177181
case <-t.C:
178182
return fmt.Errorf("timeout")
179-
default:
180-
conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))
181-
if err != nil {
182-
time.Sleep(time.Millisecond * 100)
183-
continue
184-
} else {
185-
_ = conn.Close()
183+
case <-ticker.C:
184+
print(".")
185+
_, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))
186+
if errors.Is(err, syscall.ECONNREFUSED) {
186187
return nil
187188
}
189+
time.Sleep(time.Millisecond * 100)
188190
}
189191
}
190192
}
191193

194+
func TestCtrlCWhenREngineIsRunning(t *testing.T) {
195+
// generate a random port
196+
port, f := GetPort()
197+
f()
198+
t.Logf("port: %d", port)
199+
200+
tmpDir := initTestEnv(t, port)
201+
// change dir to tmpDir
202+
err := os.Chdir(tmpDir)
203+
if err != nil {
204+
t.Fatalf("Should not be fail: %s.", err)
205+
}
206+
engine, err := NewEngine("", true)
207+
if err != nil {
208+
t.Fatalf("Should not be fail: %s.", err)
209+
}
210+
go func() {
211+
engine.Run()
212+
t.Logf("engine stopped")
213+
}()
214+
sigs := make(chan os.Signal, 1)
215+
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
216+
go func() {
217+
<-sigs
218+
engine.Stop()
219+
t.Logf("engine stopped")
220+
}()
221+
if err := waitingPortReady(port, time.Second*5); err != nil {
222+
t.Fatalf("Should not be fail: %s.", err)
223+
}
224+
sigs <- syscall.SIGINT
225+
time.Sleep(time.Second * 1)
226+
err = waitingPortConnectionRefused(port, time.Second*10)
227+
if err != nil {
228+
t.Fatalf("Should not be fail: %s.", err)
229+
}
230+
}
231+
192232
// waitingPortReady waits until the port is ready to be used.
193233
func waitingPortReady(port int, timeout time.Duration) error {
194234
timeoutChan := time.After(timeout)

0 commit comments

Comments
 (0)