2
0

costmodel_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package costmodel
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "testing"
  7. "time"
  8. "github.com/opencost/opencost/pkg/costmodel"
  9. "github.com/opencost/opencost/pkg/env"
  10. )
  11. func TestMCPServerGracefulShutdown(t *testing.T) {
  12. ctx, cancel := context.WithCancel(context.Background())
  13. defer cancel()
  14. accesses := &costmodel.Accesses{}
  15. port := env.GetMCPHTTPPort()
  16. // Start MCP server
  17. go func() {
  18. _ = StartMCPServer(ctx, accesses, nil)
  19. }()
  20. // Wait for server to be ready
  21. serverUp := false
  22. for i := 0; i < 10; i++ {
  23. time.Sleep(100 * time.Millisecond)
  24. client := &http.Client{Timeout: 1 * time.Second}
  25. resp, err := client.Get(fmt.Sprintf("http://localhost:%d/", port))
  26. if err == nil {
  27. resp.Body.Close()
  28. serverUp = true
  29. break
  30. }
  31. }
  32. if !serverUp {
  33. t.Skip("MCP server did not start")
  34. }
  35. // Trigger shutdown
  36. cancel()
  37. time.Sleep(500 * time.Millisecond)
  38. // Verify server is no longer accepting connections
  39. client := &http.Client{Timeout: 500 * time.Millisecond}
  40. _, err := client.Get(fmt.Sprintf("http://localhost:%d/", port))
  41. if err == nil {
  42. t.Error("Server still accepting connections after shutdown")
  43. }
  44. }
  45. // TestShutdownTimeoutConstant verifies the shutdown timeout constant is set correctly
  46. func TestShutdownTimeoutConstant(t *testing.T) {
  47. if shutdownTimeout != 30*time.Second {
  48. t.Errorf("Expected shutdown timeout of 30s, got %v", shutdownTimeout)
  49. }
  50. }
  51. // TestGracefulShutdownConfiguration verifies graceful shutdown works with the configured timeout
  52. func TestGracefulShutdownConfiguration(t *testing.T) {
  53. if shutdownTimeout < 5*time.Second {
  54. t.Error("Shutdown timeout is too short for graceful shutdown")
  55. }
  56. }