|
| 1 | +package viamserver |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "net" |
| 7 | + "net/http" |
| 8 | + "sync" |
| 9 | + "testing" |
| 10 | + |
| 11 | + "go.viam.com/rdk/logging" |
| 12 | + "go.viam.com/test" |
| 13 | + "go.viam.com/utils" |
| 14 | +) |
| 15 | + |
| 16 | +func TestCheckRestartProperty(t *testing.T) { |
| 17 | + logger := logging.NewTestLogger(t) |
| 18 | + ctx := context.Background() |
| 19 | + |
| 20 | + expectedRestartStatusResponse := RestartStatusResponse{ |
| 21 | + RestartAllowed: false, |
| 22 | + DoesNotHandleNeedsRestart: true, |
| 23 | + } |
| 24 | + |
| 25 | + // Set up an HTTP server that reports the expected RestartStatusResponse at the address |
| 26 | + // http://localhost:8080/restart_status. |
| 27 | + mux := http.NewServeMux() |
| 28 | + mux.HandleFunc("/restart_status", func(w http.ResponseWriter, _ *http.Request) { |
| 29 | + w.Header().Set("Content-Type", "application/json") |
| 30 | + test.That(t, json.NewEncoder(w).Encode(expectedRestartStatusResponse), test.ShouldBeNil) |
| 31 | + }) |
| 32 | + // Use NewPossiblySecureHTTPServer to mimic RDK's behavior. |
| 33 | + httpServer, err := utils.NewPossiblySecureHTTPServer(mux, utils.HTTPServerOptions{ |
| 34 | + Secure: false, |
| 35 | + Addr: "localhost:8080", |
| 36 | + }) |
| 37 | + test.That(t, err, test.ShouldBeNil) |
| 38 | + ln, err := net.Listen("tcp", "localhost:8080") |
| 39 | + test.That(t, err, test.ShouldBeNil) |
| 40 | + var wg sync.WaitGroup |
| 41 | + wg.Add(1) |
| 42 | + go func() { |
| 43 | + defer wg.Done() |
| 44 | + err := httpServer.Serve(ln) |
| 45 | + if err != nil { |
| 46 | + println(err.Error()) |
| 47 | + } |
| 48 | + }() |
| 49 | + t.Cleanup(func() { |
| 50 | + test.That(t, httpServer.Shutdown(ctx), test.ShouldBeNil) |
| 51 | + wg.Wait() |
| 52 | + }) |
| 53 | + |
| 54 | + // Create a new viamserver object with mostly empty fields except for checkURL and |
| 55 | + // checkURLAlt. |
| 56 | + s := &viamServer{ |
| 57 | + logger: logger, |
| 58 | + checkURL: "http://localhost:8080", |
| 59 | + checkURLAlt: "http://127.0.0.1:8080", |
| 60 | + } |
| 61 | + |
| 62 | + // Run checkRestartProperty on the viamserver object and ensure that expected values are |
| 63 | + // returned with no errors. |
| 64 | + s.mu.Lock() |
| 65 | + restartAllowed, err := s.checkRestartProperty(ctx, RestartPropertyRestartAllowed) |
| 66 | + s.mu.Unlock() |
| 67 | + test.That(t, err, test.ShouldBeNil) |
| 68 | + test.That(t, restartAllowed, test.ShouldEqual, expectedRestartStatusResponse.RestartAllowed) |
| 69 | + |
| 70 | + s.mu.Lock() |
| 71 | + doesNotHandle, err := s.checkRestartProperty(ctx, RestartPropertyDoesNotHandleNeedsRestart) |
| 72 | + s.mu.Unlock() |
| 73 | + test.That(t, err, test.ShouldBeNil) |
| 74 | + test.That(t, doesNotHandle, test.ShouldEqual, expectedRestartStatusResponse.DoesNotHandleNeedsRestart) |
| 75 | +} |
0 commit comments