Files

102 lines
2.8 KiB
Go
Raw Permalink Normal View History

package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"cloudipvalidator/internal/db"
"cloudipvalidator/internal/openstack"
)
type gatedDiagnosticCloud struct {
*openstack.MockClient
started chan struct{}
proceed chan struct{}
}
func (c *gatedDiagnosticCloud) AssociateFloatingIP(ctx context.Context, fipID, portID string) error {
close(c.started)
select {
case <-ctx.Done():
return ctx.Err()
case <-c.proceed:
return c.MockClient.AssociateFloatingIP(ctx, fipID, portID)
}
}
func TestDiagnosticOperationAcceptedWhileNeutronRuns(t *testing.T) {
s, _ := newAuthTestServer(t, testAdminToken, testAgentToken)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
mock := s.Orch.OS.(*openstack.MockClient)
mock.Seed("fip", "203.0.113.5", "test")
cloud := &gatedDiagnosticCloud{MockClient: mock, started: make(chan struct{}), proceed: make(chan struct{})}
s.Orch.OS = cloud
if err := s.DB.RegisterValidator(ctx, "validator", "host", "port", "v"); err != nil {
t.Fatal(err)
}
done := make(chan struct{})
go func() {
defer close(done)
s.Orch.RunDiagnosticOperations(ctx)
}()
defer func() {
cancel()
<-done
}()
handler := s.Handler()
call := func(method, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequestWithContext(ctx, method, path, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+testAdminToken)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
return rec
}
const operations = "/api/v1/admin/diagnostics/operations"
const id = "api-diagnostic-operation"
const requestBody = `{"id":"` + id + `","items":[{"address":"203.0.113.5","validator_id":"validator"}]}`
rec := call(http.MethodPost, operations, requestBody)
if rec.Code != http.StatusAccepted || rec.Header().Get("Location") != operations+"/"+id {
t.Fatalf("start: %d, %v, %s", rec.Code, rec.Header(), rec.Body)
}
select {
case <-cloud.started:
case <-ctx.Done():
t.Fatal("Neutron association did not start")
}
rec = call(http.MethodPost, operations, requestBody)
if rec.Code != http.StatusAccepted {
t.Fatalf("retry: %d %s", rec.Code, rec.Body)
}
var op db.DiagnosticOperation
readOperation := func() {
t.Helper()
rec := call(http.MethodGet, operations+"/"+id, "")
err := json.Unmarshal(rec.Body.Bytes(), &op)
if rec.Code != http.StatusOK || err != nil || len(op.Items) != 1 {
t.Fatalf("get: %d %s, %v", rec.Code, rec.Body, err)
}
}
readOperation()
if op.Items[0].Status != "running" {
t.Fatalf("before Neutron confirms: %+v", op)
}
close(cloud.proceed)
for {
readOperation()
if op.Items[0].Status == "attached" {
break
}
select {
case <-time.After(10 * time.Millisecond):
case <-ctx.Done():
t.Fatalf("final status: %+v", op)
}
}
}