فهرست منبع

test(server): Fase 6.5 — tests de display-name, system/info y clave vm en overview

- Roundtrip PUT /api/users/me/display-name: trim, 204, persistencia en DB,
  400 con 41 runes / con '<''>' / body inválido, vacío permitido
- GET /api/users incluye displayName; /api/auth/me gana la clave
- Parseadores puros de system/info con fixtures os-release/cpuinfo/meminfo
- Endpoint /api/system/info: 401 sin sesión, forma exacta de 11 claves
- TestOverviewProtegido exige vm=1
agent 4 ماه پیش
والد
کامیت
a989fea0a9

+ 131 - 0
server-go/internal/httpapi/display_name_test.go

@@ -0,0 +1,131 @@
+package httpapi_test
+
+import (
+	"fmt"
+	"net/http"
+	"strings"
+	"testing"
+)
+
+// SPEC-65 D65-5: display name por usuario — roundtrip completo.
+func TestDisplayNameRoundtrip(t *testing.T) {
+	srv := makeTestServer(t)
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+
+	// Al inicio: displayName "" (no puesto)
+	res := get(t, srv.URL, "/api/auth/me", cookie)
+	body := readJSON(t, res)
+	if body["displayName"] != "" {
+		t.Fatalf("displayName inicial: %v", body)
+	}
+
+	put := func(payload string) (int, map[string]any) {
+		req, _ := http.NewRequest("PUT", srv.URL+"/api/users/me/display-name", strings.NewReader(payload))
+		req.Header.Set("Cookie", "session="+cookie)
+		res, err := http.DefaultClient.Do(req)
+		if err != nil {
+			t.Fatalf("PUT display-name: %v", err)
+		}
+		if res.StatusCode == 204 {
+			res.Body.Close()
+			return res.StatusCode, nil
+		}
+		return res.StatusCode, readJSON(t, res)
+	}
+
+	// Guardar (con espacios alrededor: se hace trim) → 204 y aparece en /me
+	st, _ := put(`{"displayName":"  Nacho 🚀  "}`)
+	if st != 204 {
+		t.Fatalf("PUT display-name: got %d want 204", st)
+	}
+	body = readJSON(t, get(t, srv.URL, "/api/auth/me", cookie))
+	if body["displayName"] != "Nacho 🚀" {
+		t.Fatalf("displayName tras guardar: %v", body)
+	}
+	// Persiste en DB (lectura directa, misma fila que sirve /me)
+	var dn string
+	if err := srv.db.QueryRow("SELECT display_name FROM users WHERE username = 'admin'").Scan(&dn); err != nil || dn != "Nacho 🚀" {
+		t.Fatalf("display_name en DB: %q err=%v", dn, err)
+	}
+
+	// 40 runes exactos → 204; 41 runes → 400
+	st, _ = put(`{"displayName":"` + strings.Repeat("á", 40) + `"}`)
+	if st != 204 {
+		t.Fatalf("40 runes: got %d want 204", st)
+	}
+	st, body = put(`{"displayName":"` + strings.Repeat("a", 41) + `"}`)
+	if st != 400 || body["error"] != "invalid_input" {
+		t.Fatalf("41 runes: got %d %v want 400", st, body)
+	}
+
+	// HTML → 400
+	st, body = put(`{"displayName":"<b>x</b>"}`)
+	if st != 400 || body["error"] != "invalid_input" {
+		t.Fatalf("con <>: got %d %v want 400", st, body)
+	}
+	st, _ = put(`{"displayName":"a>b"}`)
+	if st != 400 {
+		t.Fatalf("con >: got %d want 400", st)
+	}
+
+	// Body inválido → 400
+	st, _ = put(`{"displayName":42}`)
+	if st != 400 {
+		t.Fatalf("tipo inválido: got %d want 400", st)
+	}
+	st, _ = put(`{}`)
+	if st != 400 {
+		t.Fatalf("sin displayName: got %d want 400", st)
+	}
+
+	// Vacío permitido (= volver al username) → 204 y displayName ""
+	st, _ = put(`{"displayName":"   "}`)
+	if st != 204 {
+		t.Fatalf("vacío: got %d want 204", st)
+	}
+	body = readJSON(t, get(t, srv.URL, "/api/auth/me", cookie))
+	if body["displayName"] != "" {
+		t.Fatalf("displayName tras vaciar: %v", body)
+	}
+}
+
+// GET /api/users incluye displayName por usuario (admin).
+func TestListUsersIncluyeDisplayName(t *testing.T) {
+	srv := makeTestServer(t)
+	_, adminCookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+
+	// Alta de una usuaria no-admin y display name propio (fuera del gate admin)
+	req, _ := http.NewRequest("POST", srv.URL+"/api/users", strings.NewReader(`{"username":"ana","password":"clave-ana-1","role":"user"}`))
+	req.Header.Set("Cookie", "session="+adminCookie)
+	res, _ := http.DefaultClient.Do(req)
+	res.Body.Close()
+	if res.StatusCode != 201 {
+		t.Fatalf("crear ana: got %d want 201", res.StatusCode)
+	}
+	_, anaCookie, _ := loginCookie(t, srv.URL, "ana", "clave-ana-1")
+	req, _ = http.NewRequest("PUT", srv.URL+"/api/users/me/display-name", strings.NewReader(`{"displayName":"Ana"}`))
+	req.Header.Set("Cookie", "session="+anaCookie)
+	res, _ = http.DefaultClient.Do(req)
+	res.Body.Close()
+	if res.StatusCode != 204 {
+		t.Fatalf("display-name no-admin: got %d want 204", res.StatusCode)
+	}
+
+	res = get(t, srv.URL, "/api/users", adminCookie)
+	body := readJSON(t, res)
+	users, ok := body["users"].([]any)
+	if !ok {
+		t.Fatalf("users: %v", body)
+	}
+	names := map[string]any{}
+	for _, u := range users {
+		m := u.(map[string]any)
+		names[fmt.Sprint(m["username"])] = m["displayName"]
+	}
+	if names["ana"] != "Ana" {
+		t.Fatalf("displayName de ana en /api/users: %v", names["ana"])
+	}
+	if names["admin"] != "" {
+		t.Fatalf("displayName de admin debería ser \"\": %v", names["admin"])
+	}
+}

+ 6 - 3
server-go/internal/httpapi/httpapi_test.go

@@ -146,7 +146,7 @@ func TestLoginCorrectoYMe(t *testing.T) {
 		t.Fatalf("me: got %d want 200", res.StatusCode)
 	}
 	body := readJSON(t, res)
-	want := map[string]any{"user": "admin", "role": "admin", "language": "auto", "mode": "demo"}
+	want := map[string]any{"user": "admin", "role": "admin", "language": "auto", "displayName": "", "mode": "demo"}
 	for k, v := range want {
 		if body[k] != v {
 			t.Fatalf("me[%s]: got %v want %v (body=%v)", k, body[k], v, body)
@@ -173,12 +173,15 @@ func TestOverviewProtegido(t *testing.T) {
 		t.Fatalf("con cookie: got %d want 200", res2.StatusCode)
 	}
 	ov := readJSON(t, res2)
-	// Shape del overview (claves del contrato)
-	for _, k := range []string{"health", "wan", "traffic", "adguard", "wireguard", "routers", "deviceTotals", "topDevices", "alerts", "unreadAlerts", "ts"} {
+	// Shape del overview (claves del contrato; vm SIEMPRE, SPEC-65 D65-4)
+	for _, k := range []string{"health", "wan", "traffic", "adguard", "wireguard", "routers", "deviceTotals", "topDevices", "alerts", "unreadAlerts", "vm", "ts"} {
 		if _, ok := ov[k]; !ok {
 			t.Fatalf("overview sin clave %q", k)
 		}
 	}
+	if ov["vm"] != float64(1) {
+		t.Fatalf("vm debe ser 1 (ViewModelVersion): %v", ov["vm"])
+	}
 	if routers, ok := ov["routers"].([]any); !ok || len(routers) != 4 {
 		t.Fatalf("routers: %v", ov["routers"])
 	}

+ 57 - 0
server-go/internal/httpapi/system_api_test.go

@@ -0,0 +1,57 @@
+package httpapi_test
+
+import (
+	"testing"
+
+	"github.com/gnacho/netpulse/server-go/internal/httpapi"
+)
+
+// SPEC-65 D65-6: GET /api/system/info — autenticado (cualquier usuario),
+// datos reales del proceso con la forma exacta del contrato.
+func TestSystemInfo(t *testing.T) {
+	srv := makeTestServer(t)
+
+	// Sin sesión → 401
+	res := get(t, srv.URL, "/api/system/info", "")
+	if res.StatusCode != 401 {
+		res.Body.Close()
+		t.Fatalf("sin cookie: got %d want 401", res.StatusCode)
+	}
+	res.Body.Close()
+
+	_, cookie, _ := loginCookie(t, srv.URL, "admin", "test1234")
+	res = get(t, srv.URL, "/api/system/info", cookie)
+	if res.StatusCode != 200 {
+		t.Fatalf("con cookie: got %d want 200", res.StatusCode)
+	}
+	body := readJSON(t, res)
+	// Forma exacta: las 11 claves del contrato, ni una más
+	want := map[string]bool{
+		"version": true, "goVersion": true, "os": true, "arch": true, "distro": true,
+		"kernel": true, "cpuModel": true, "cpuCores": true, "memTotalMb": true,
+		"uptimeS": true, "demo": true,
+	}
+	if len(body) != len(want) {
+		t.Fatalf("claves: got %v", body)
+	}
+	for k := range want {
+		if _, ok := body[k]; !ok {
+			t.Fatalf("falta clave %q en %v", k, body)
+		}
+	}
+	if body["version"] != httpapi.Version {
+		t.Fatalf("version=%v, want %s (misma fuente que update.go)", body["version"], httpapi.Version)
+	}
+	if goVer, ok := body["goVersion"].(string); !ok || len(goVer) < 3 || goVer[:2] != "go" {
+		t.Fatalf("goVersion: %v", body["goVersion"])
+	}
+	if cores, ok := body["cpuCores"].(float64); !ok || cores < 1 {
+		t.Fatalf("cpuCores: %v", body["cpuCores"])
+	}
+	if up, ok := body["uptimeS"].(float64); !ok || up < 0 {
+		t.Fatalf("uptimeS: %v", body["uptimeS"])
+	}
+	if body["demo"] != true {
+		t.Fatalf("demo: %v (el servidor de test es DEMO_MODE=1)", body["demo"])
+	}
+}

+ 58 - 0
server-go/internal/httpapi/system_internal_test.go

@@ -0,0 +1,58 @@
+package httpapi
+
+import "testing"
+
+// Tests de los parseadores puros de /api/system/info (SPEC-65 D65-6) con
+// fixtures literales de /etc/os-release, /proc/cpuinfo y /proc/meminfo.
+
+func TestParseOsReleasePretty(t *testing.T) {
+	cases := []struct {
+		name, content, want string
+	}{
+		{"debian", "NAME=\"Debian GNU/Linux\"\nVERSION_ID=\"12\"\nPRETTY_NAME=\"Debian GNU/Linux 12 (bookworm)\"\n", "Debian GNU/Linux 12 (bookworm)"},
+		{"sin comillas", "PRETTY_NAME=Ubuntu 24.04 LTS\nNAME=Ubuntu\n", "Ubuntu 24.04 LTS"},
+		{"openwrt", "NAME=\"OpenWrt\"\nPRETTY_NAME=\"OpenWrt 24.10.1\"\n", "OpenWrt 24.10.1"},
+		{"ausente", "NAME=\"Algo\"\nVERSION_ID=\"1\"\n", ""},
+		{"vacío", "", ""},
+	}
+	for _, c := range cases {
+		if got := parseOsReleasePretty(c.content); got != c.want {
+			t.Fatalf("%s: parseOsReleasePretty=%q, want %q", c.name, got, c.want)
+		}
+	}
+}
+
+func TestParseCPUModel(t *testing.T) {
+	x86 := "processor\t: 0\nvendor_id\t: GenuineIntel\nmodel name\t: Intel(R) N100\n\ncpu cores\t: 4\n"
+	if got := parseCPUModel(x86); got != "Intel(R) N100" {
+		t.Fatalf("x86: %q", got)
+	}
+	arm := "processor\t: 0\nBogoMIPS\t: 38.40\nFeatures\t: fp asimd\nCPU implementer\t: 0x41\nModel\t\t: Raspberry Pi 4 Model B Rev 1.4\n"
+	if got := parseCPUModel(arm); got != "Raspberry Pi 4 Model B Rev 1.4" {
+		t.Fatalf("arm: %q", got)
+	}
+	// model name gana aunque haya varias entradas (la primera)
+	multi := "model name\t: Fake CPU A\n\nmodel name\t: Fake CPU B\n"
+	if got := parseCPUModel(multi); got != "Fake CPU A" {
+		t.Fatalf("multi: %q", got)
+	}
+	if got := parseCPUModel("nada\nque\tvalga\n"); got != "" {
+		t.Fatalf("sin modelo: %q", got)
+	}
+}
+
+func TestParseMemTotalMB(t *testing.T) {
+	mem := "MemTotal:        8175476 kB\nMemFree:         1234567 kB\nMemAvailable:    4000000 kB\n"
+	if got := parseMemTotalMB(mem); got != 8175476/1024 {
+		t.Fatalf("memTotal: %d", got)
+	}
+	if got := parseMemTotalMB("MemFree: 10 kB\n"); got != 0 {
+		t.Fatalf("sin MemTotal: %d", got)
+	}
+	if got := parseMemTotalMB("MemTotal: abc kB\n"); got != 0 {
+		t.Fatalf("MemTotal inválido: %d", got)
+	}
+	if got := parseMemTotalMB(""); got != 0 {
+		t.Fatalf("vacío: %d", got)
+	}
+}