This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package networkapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/itworx/pulse/internal/auth"
|
||||
"github.com/itworx/pulse/internal/network"
|
||||
)
|
||||
|
||||
type staticProvider struct {
|
||||
snapshot network.Snapshot
|
||||
err error
|
||||
}
|
||||
|
||||
func (p staticProvider) Snapshot(context.Context) (network.Snapshot, error) { return p.snapshot, p.err }
|
||||
|
||||
func authenticatedNetworkRequest() *http.Request {
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/v1/network", nil)
|
||||
return r.WithContext(auth.WithPrincipal(r.Context(), auth.Principal{Subject: "viewer", Role: auth.RoleViewer}))
|
||||
}
|
||||
|
||||
func TestNetworkHandlerAuthAndSafeOutput(t *testing.T) {
|
||||
handler := Handler{Provider: staticProvider{snapshot: network.Snapshot{ContractVersion: network.ContractVersion, ObservedAt: time.Now().UTC(), Health: []network.Health{{Scope: network.ScopeInternet, State: network.StateDown, Reason: "target_failed"}}}}}
|
||||
unauthorized := httptest.NewRecorder()
|
||||
handler.ServeHTTP(unauthorized, httptest.NewRequest(http.MethodGet, "/api/v1/network", nil))
|
||||
if unauthorized.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("unauthorized status=%d", unauthorized.Code)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, authenticatedNetworkRequest())
|
||||
if response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"scope":"internet"`) || !strings.Contains(response.Body.String(), `"state":"down"`) {
|
||||
t.Fatalf("status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetworkHandlerMapsProviderFailure(t *testing.T) {
|
||||
handler := Handler{Provider: staticProvider{err: errors.New("source down")}}
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, authenticatedNetworkRequest())
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status=%d", response.Code)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user