Files

84 lines
2.4 KiB
Go

package main
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
"testing"
"time"
"alice-back/station/pcaudio"
)
func TestPCAudioWaitsForAgentAndExpires(t *testing.T) {
const token = "test-token"
control := &pcAudioControl{
token: token, peer: netip.MustParseAddr("192.0.2.10"), desired: newPCCommand(false),
}
poll := func(state pcaudio.State, key string) (pcaudio.Command, int) {
data, _ := json.Marshal(state)
req := httptest.NewRequest(http.MethodPost, pcaudio.Path, bytes.NewReader(data))
req.RemoteAddr = "192.0.2.10:42000"
req.Header.Set("Authorization", "Bearer "+key)
response := httptest.NewRecorder()
control.ServeHTTP(response, req)
var cmd pcaudio.Command
if response.Code == http.StatusOK {
if err := json.Unmarshal(response.Body.Bytes(), &cmd); err != nil {
t.Fatal(err)
}
}
return cmd, response.Code
}
if _, code := poll(pcaudio.State{}, "wrong"); code != http.StatusForbidden {
t.Fatalf("accepted unauthorized request: %d", code)
}
if result := control.run(context.Background(), "start"); !strings.Contains(string(result), "offline") {
t.Fatalf("started while the PC was offline: %s", result)
}
initial, _ := poll(pcaudio.State{}, token)
if initial.Enabled {
t.Fatal("initial command enabled audio")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
done := make(chan json.RawMessage, 1)
go func() { done <- control.run(ctx, "start") }()
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
seen := initial
for !seen.Enabled {
select {
case <-ctx.Done():
t.Fatal("start command did not reach the agent")
case <-ticker.C:
seen, _ = poll(pcaudio.State{Command: initial}, token)
}
}
select {
case result := <-done:
t.Fatalf("start reported success before acknowledgment: %s", result)
default:
}
poll(pcaudio.State{Command: seen}, token)
select {
case result := <-done:
if string(result) != `{"enabled":true,"ok":true}` {
t.Fatalf("start result: %s", result)
}
case <-ctx.Done():
t.Fatal("start acknowledgment was not returned")
}
control.mu.Lock()
control.last = time.Now().Add(-pcAudioLease)
control.mu.Unlock()
expired, _ := poll(pcaudio.State{Command: seen}, token)
if expired.Enabled || expired.Revision == seen.Revision {
t.Fatal("reconnecting agent would automatically restart streaming")
}
}