|
| 1 | +package internal_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "syscall" |
| 9 | + "testing" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/leetcode-golang-classroom/golang-graceful-shutdown-concept/internal" |
| 13 | +) |
| 14 | + |
| 15 | +func TestServerGracefulShutdown(t *testing.T) { |
| 16 | + slowResponse := 2 * time.Second |
| 17 | + server := internal.NewServer(":3000", func(w http.ResponseWriter, r *http.Request) { |
| 18 | + time.Sleep(slowResponse) |
| 19 | + w.Write([]byte("completed")) |
| 20 | + }) |
| 21 | + |
| 22 | + serverErrorCh := make(chan error) |
| 23 | + go func() { |
| 24 | + serverErrorCh <- server.Run(context.Background(), 5*time.Second) |
| 25 | + }() |
| 26 | + time.Sleep(1 * time.Millisecond) |
| 27 | + resp, err := http.Get("http://localhost" + server.AppServer.Addr + "/slow") |
| 28 | + |
| 29 | + syscall.Kill(syscall.Getpid(), syscall.SIGINT) |
| 30 | + |
| 31 | + if err != nil { |
| 32 | + t.Fatalf("unable to send request to server: %v", err) |
| 33 | + } |
| 34 | + |
| 35 | + if resp.StatusCode != http.StatusOK { |
| 36 | + t.Errorf("expected 200 StatusOK, got %d", resp.StatusCode) |
| 37 | + } |
| 38 | + |
| 39 | + body, err := io.ReadAll(resp.Body) |
| 40 | + if err != nil { |
| 41 | + t.Fatalf("unable to read body: %v\n", err) |
| 42 | + } |
| 43 | + |
| 44 | + if string(body) != "completed" { |
| 45 | + t.Errorf("expected body 'completed', got %s", string(body)) |
| 46 | + } |
| 47 | + |
| 48 | + serverErr := <-serverErrorCh |
| 49 | + if serverErr != nil { |
| 50 | + t.Fatalf("expected no server error, got %v", serverErr) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +func TestServerTimeoutDuringShutdown(t *testing.T) { |
| 55 | + slowResponse := 10 * time.Second |
| 56 | + server := internal.NewServer(":3001", func(w http.ResponseWriter, r *http.Request) { |
| 57 | + time.Sleep(slowResponse) |
| 58 | + w.Write([]byte("completed")) |
| 59 | + }) |
| 60 | + |
| 61 | + serverErrorCh := make(chan error) |
| 62 | + go func() { |
| 63 | + serverErrorCh <- server.Run(context.Background(), 5*time.Millisecond) |
| 64 | + }() |
| 65 | + requestErrorCh := make(chan error) |
| 66 | + go func() { |
| 67 | + _, err := http.Get("http://localhost" + server.AppServer.Addr + "/slow") |
| 68 | + requestErrorCh <- err |
| 69 | + }() |
| 70 | + |
| 71 | + time.Sleep(1 * time.Second) |
| 72 | + syscall.Kill(syscall.Getpid(), syscall.SIGINT) |
| 73 | + |
| 74 | + if <-requestErrorCh == nil { |
| 75 | + t.Errorf("expected client request to fail, but it successded") |
| 76 | + } |
| 77 | + |
| 78 | + serverErr := <-serverErrorCh |
| 79 | + if !errors.Is(serverErr, context.DeadlineExceeded) { |
| 80 | + t.Errorf("expected 'context.DeadlineExceeded' error, got %v", serverErr) |
| 81 | + } |
| 82 | +} |
0 commit comments