package web
import (
"bufio"
"context"
"io"
"net/http"
"net/url"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestEvents_SendsPingWhenIdle(t *testing.T) {
old := pingInterval
pingInterval = 20 * time.Millisecond
t.Cleanup(func() { pingInterval = old })
srv, _, _, _ := newTestServer(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/events", nil)
require.NoError(t, err)
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
reader := bufio.NewReader(resp.Body)
for {
line, err := reader.ReadString('\n')
require.NoError(t, err)
if strings.HasPrefix(line, "event:") {
assert.Equal(t, "event: ping\n", line, "the Live box counts a named event; a comment would not reach the browser's listeners")
return
}
}
}
func TestCreateAgent_ValidationShowsInsideTheAddPanel(t *testing.T) {
srv, _, _, _ := newTestServer(t)
resp, err := http.PostForm(srv.URL+"/agents", url.Values{"name": {"node-2"}})
require.NoError(t, err)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
assert.Equal(t, http.StatusConflict, resp.StatusCode)
assert.Contains(t, string(body), `class="drawer"`)
assert.Contains(t, string(body), `value="node-2"`, "the typed name is kept")
assert.NotContains(t, string(body), "pua_", "no token is shown")
}
func TestNavFragment(t *testing.T) {
srv, _, _, _ := newTestServer(t)
cases := []struct {
query, want, notWant string
}{
{"?section=agents", `Agents 1/3`, `Services 4`, `Jobs`, `class="cur"`},
}
for _, c := range cases {
t.Run(c.query, func(t *testing.T) {
code, body := get(t, srv, "/fragments/nav"+c.query)
assert.Equal(t, http.StatusOK, code)
assert.NotContains(t, body, "