Accept applied/reverted/failed in device status reports
This commit is contained in:
@@ -383,13 +383,15 @@ func (s *Server) handleDeviceRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (s *Server) handleDeviceStatus(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Generation int64 `json:"generation"`
|
||||
}
|
||||
var body model.StatusReport
|
||||
if !decode(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if err := s.store.RecordDeviceStatus(r.Context(), chi.URLParam(r, "name"), body.Generation); err != nil {
|
||||
if err := body.Normalize(); err != nil {
|
||||
writeError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := s.store.RecordDeviceStatus(r.Context(), chi.URLParam(r, "name"), body); err != nil {
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
writeError(w, http.StatusNotFound, "device not found")
|
||||
return
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.unkin.net/unkin/tomswallapi/internal/model"
|
||||
)
|
||||
|
||||
func TestStatusReportNormalize(t *testing.T) {
|
||||
tests := []struct {
|
||||
in model.ApplyStatus
|
||||
want model.ApplyStatus
|
||||
wantErr bool
|
||||
}{
|
||||
{in: "", want: model.StatusApplied},
|
||||
{in: model.StatusApplied, want: model.StatusApplied},
|
||||
{in: model.StatusReverted, want: model.StatusReverted},
|
||||
{in: model.StatusFailed, want: model.StatusFailed},
|
||||
{in: "rolledback", wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
r := model.StatusReport{Status: tt.in, Generation: 3}
|
||||
err := r.Normalize()
|
||||
if (err != nil) != tt.wantErr || (!tt.wantErr && r.Status != tt.want) {
|
||||
t.Errorf("Normalize(%q) = %q, %v", tt.in, r.Status, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleDeviceStatusRejectsBadPayload(t *testing.T) {
|
||||
s := &Server{} // nil store: a 400 must return before any DB access
|
||||
for _, body := range []string{
|
||||
`{"status":"rolledback","generation":3}`,
|
||||
`{"generation":3,"bogus":1}`,
|
||||
} {
|
||||
rec := httptest.NewRecorder()
|
||||
s.handleDeviceStatus(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(body)))
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Errorf("%s: got %d, want 400", body, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user