|
| 1 | +package server |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "strconv" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/langgenius/dify-plugin-daemon/internal/types/app" |
| 10 | + "github.com/langgenius/dify-plugin-daemon/pkg/utils/network" |
| 11 | + "github.com/langgenius/dify-plugin-daemon/pkg/utils/routine" |
| 12 | +) |
| 13 | + |
| 14 | +func TestServerHostBinding(t *testing.T) { |
| 15 | + tests := []struct { |
| 16 | + name string |
| 17 | + host string |
| 18 | + connectToHost string |
| 19 | + wantStatusCode int |
| 20 | + }{ |
| 21 | + { |
| 22 | + name: "default host 0.0.0.0", |
| 23 | + host: "0.0.0.0", |
| 24 | + connectToHost: "127.0.0.1", |
| 25 | + wantStatusCode: http.StatusOK, |
| 26 | + }, |
| 27 | + { |
| 28 | + name: "localhost", |
| 29 | + host: "127.0.0.1", |
| 30 | + connectToHost: "127.0.0.1", |
| 31 | + wantStatusCode: http.StatusOK, |
| 32 | + }, |
| 33 | + } |
| 34 | + |
| 35 | + for _, tt := range tests { |
| 36 | + t.Run(tt.name, func(t *testing.T) { |
| 37 | + port, err := network.GetRandomPort() |
| 38 | + if err != nil { |
| 39 | + t.Errorf("failed to get random port: %s", err.Error()) |
| 40 | + return |
| 41 | + } |
| 42 | + |
| 43 | + config := &app.Config{ |
| 44 | + ServerPort: port, |
| 45 | + ServerHost: tt.host, |
| 46 | + ServerKey: "test-key", |
| 47 | + HealthApiLogEnabled: true, |
| 48 | + RoutinePoolSize: 100, |
| 49 | + } |
| 50 | + config.SetDefault() |
| 51 | + |
| 52 | + routine.InitPool(config.RoutinePoolSize) |
| 53 | + |
| 54 | + appInstance := &App{} |
| 55 | + cancel := appInstance.server(config) |
| 56 | + |
| 57 | + if cancel == nil { |
| 58 | + t.Errorf("failed to start server") |
| 59 | + return |
| 60 | + } |
| 61 | + defer cancel() |
| 62 | + |
| 63 | + time.Sleep(100 * time.Millisecond) |
| 64 | + |
| 65 | + client := &http.Client{Timeout: 5 * time.Second} |
| 66 | + url := "http://" + tt.connectToHost + ":" + strconv.Itoa(int(config.ServerPort)) + "/health/check" |
| 67 | + |
| 68 | + req, err := http.NewRequest("GET", url, nil) |
| 69 | + if err != nil { |
| 70 | + t.Errorf("failed to create request: %s", err.Error()) |
| 71 | + return |
| 72 | + } |
| 73 | + |
| 74 | + resp, err := client.Do(req) |
| 75 | + if err != nil { |
| 76 | + t.Errorf("failed to send request: %s", err.Error()) |
| 77 | + return |
| 78 | + } |
| 79 | + defer resp.Body.Close() |
| 80 | + |
| 81 | + if resp.StatusCode != tt.wantStatusCode { |
| 82 | + t.Errorf("expected status %d, got %d", tt.wantStatusCode, resp.StatusCode) |
| 83 | + } |
| 84 | + }) |
| 85 | + } |
| 86 | +} |
0 commit comments