updater_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. // updater_test.go — check contra API GitHub simulada (httptest) y shape del
  2. // estado; apply con script sintético (STEP:*/exit).
  3. package updater
  4. import (
  5. "context"
  6. "fmt"
  7. "net/http"
  8. "net/http/httptest"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "strings"
  13. "sync"
  14. "sync/atomic"
  15. "testing"
  16. "time"
  17. )
  18. func gitAvailable() bool { _, err := exec.LookPath("git"); return err == nil }
  19. func withAPI(t *testing.T, h http.HandlerFunc) {
  20. t.Helper()
  21. srv := httptest.NewServer(h)
  22. t.Cleanup(srv.Close)
  23. old := APIBase
  24. APIBase = srv.URL
  25. t.Cleanup(func() { APIBase = old })
  26. // El check de conectividad del readiness usa probeURL (web pública de
  27. // GitHub, #956): apuntarlo también al httptest para tests herméticos.
  28. oldProbe := probeURL
  29. probeURL = srv.URL
  30. t.Cleanup(func() { probeURL = oldProbe })
  31. }
  32. func TestCheckUpdateAvailable(t *testing.T) {
  33. withAPI(t, func(w http.ResponseWriter, r *http.Request) {
  34. switch r.URL.Path {
  35. case "/repos/owner/netpulse/commits/main":
  36. w.Header().Set("Content-Type", "application/json")
  37. fmt.Fprint(w, `{"sha":"abc1234deadbeef","commit":{"message":"feat: algo\n\nbody"}}`)
  38. case "/repos/owner/netpulse/releases":
  39. w.Header().Set("Content-Type", "application/json")
  40. fmt.Fprint(w, `[]`)
  41. case "/repos/owner/netpulse/releases/latest":
  42. w.Header().Set("Content-Type", "application/json")
  43. fmt.Fprint(w, `{"tag_name":"v2.5.0"}`)
  44. default:
  45. // Compare del changelog (issue #490): cualquier path /compare/.
  46. if strings.Contains(r.URL.Path, "/compare/") {
  47. w.Header().Set("Content-Type", "application/json")
  48. fmt.Fprint(w, `{"commits":[{"sha":"abc1234deadbeef","commit":{"message":"feat: algo"}}]}`)
  49. return
  50. }
  51. t.Errorf("path: %s", r.URL.Path)
  52. }
  53. })
  54. // repoRoot con git válido (commit distinto) para updateAvailable.
  55. // deploy/update.sh → modo rolling (compara contra main HEAD).
  56. root := t.TempDir()
  57. writeDeployScript(t, root)
  58. writeGitHead(t, root)
  59. u := New(root, "owner/netpulse", "", "2.0.0", nil)
  60. st := u.Check(context.Background())
  61. if st.Error != nil {
  62. t.Fatalf("error: %v", *st.Error)
  63. }
  64. if st.Latest == nil || *st.Latest != "abc1234" {
  65. t.Fatalf("latest: %v", st.Latest)
  66. }
  67. if st.LatestMsg == nil || *st.LatestMsg != "feat: algo" {
  68. t.Fatalf("latestMsg: %v", st.LatestMsg)
  69. }
  70. // Issue #280: el body del commit llega como changelog del asistente.
  71. if st.LatestBody == nil || *st.LatestBody != "body" {
  72. t.Fatalf("latestBody: %v", st.LatestBody)
  73. }
  74. if !st.UpdateAvailable {
  75. t.Fatalf("debería haber update: %+v", st)
  76. }
  77. if !st.CanApply || st.Mode != "rolling" {
  78. t.Fatalf("debería ser rolling/canApply: canApply=%v mode=%s", st.CanApply, st.Mode)
  79. }
  80. if st.Updating != false || st.HasToken || st.Repo != "owner/netpulse" {
  81. t.Fatalf("shape: %+v", st)
  82. }
  83. if st.LastCheck == nil {
  84. t.Fatal("lastCheck nil")
  85. }
  86. }
  87. // Issue #404: si el body del commit está vacío, el backend debe buscar las
  88. // notas del release asociado al commit y devolverlas como changelog.
  89. func TestCheckUsesReleaseBodyWhenCommitBodyEmpty(t *testing.T) {
  90. withAPI(t, func(w http.ResponseWriter, r *http.Request) {
  91. switch r.URL.Path {
  92. case "/repos/owner/netpulse/commits/main":
  93. w.Header().Set("Content-Type", "application/json")
  94. fmt.Fprint(w, `{"sha":"deadbeefabc1234","commit":{"message":"chore(release): v2.5.0"}}`)
  95. case "/repos/owner/netpulse/releases":
  96. w.Header().Set("Content-Type", "application/json")
  97. fmt.Fprint(w, `[{"body":"Release notes line 1\nRelease notes line 2","target_commitish":"deadbeefabc1234"}]`)
  98. case "/repos/owner/netpulse/releases/latest":
  99. w.Header().Set("Content-Type", "application/json")
  100. fmt.Fprint(w, `{"tag_name":"v2.5.0"}`)
  101. default:
  102. // Compare del changelog (issue #490).
  103. if strings.Contains(r.URL.Path, "/compare/") {
  104. fmt.Fprint(w, `{"commits":[]}`)
  105. return
  106. }
  107. t.Errorf("path: %s", r.URL.Path)
  108. }
  109. })
  110. root := t.TempDir()
  111. writeDeployScript(t, root)
  112. writeGitHead(t, root)
  113. u := New(root, "owner/netpulse", "", "2.0.0", nil)
  114. st := u.Check(context.Background())
  115. if st.Error != nil {
  116. t.Fatalf("error: %v", *st.Error)
  117. }
  118. if st.LatestBody == nil || *st.LatestBody != "Release notes line 1\nRelease notes line 2" {
  119. t.Fatalf("latestBody: %v", st.LatestBody)
  120. }
  121. }
  122. func TestCheckNoToken(t *testing.T) {
  123. withAPI(t, func(w http.ResponseWriter, r *http.Request) {
  124. w.WriteHeader(http.StatusNotFound)
  125. })
  126. // Sin deploy/update.sh → modo estable. El 404 llega tanto a /releases/latest
  127. // como a /commits/main; el error es el mismo.
  128. u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", nil)
  129. st := u.Check(context.Background())
  130. if st.Error == nil || *st.Error != "no_token" {
  131. t.Fatalf("error: %v", st.Error)
  132. }
  133. if st.CanApply || st.Mode != "stable" {
  134. t.Fatalf("debería ser stable/!canApply: canApply=%v mode=%s", st.CanApply, st.Mode)
  135. }
  136. }
  137. func TestCheckMismaVersion(t *testing.T) {
  138. root := t.TempDir()
  139. writeDeployScript(t, root) // modo rolling
  140. short := writeGitHead(t, root)
  141. withAPI(t, func(w http.ResponseWriter, r *http.Request) {
  142. fmt.Fprintf(w, `{"sha":"%sffffffffff","commit":{"message":"x"}}`, short)
  143. })
  144. u := New(root, "owner/netpulse", "", "2.0.0", nil)
  145. st := u.Check(context.Background())
  146. if st.UpdateAvailable {
  147. t.Fatal("no debería haber update")
  148. }
  149. }
  150. // writeGitHead crea un repo git mínimo con un commit y devuelve su short SHA.
  151. func writeGitHead(t *testing.T, root string) string {
  152. t.Helper()
  153. if !gitAvailable() {
  154. t.Skip("git no disponible")
  155. }
  156. run := func(args ...string) {
  157. cmd := exec.Command("git", append([]string{"-C", root}, args...)...)
  158. if out, err := cmd.CombinedOutput(); err != nil {
  159. t.Fatalf("git %v: %v %s", args, err, out)
  160. }
  161. }
  162. run("init", "-q")
  163. run("config", "user.email", "t@t")
  164. run("config", "user.name", "t")
  165. if err := os.WriteFile(filepath.Join(root, "f"), []byte("x"), 0o644); err != nil {
  166. t.Fatal(err)
  167. }
  168. run("add", ".")
  169. run("commit", "-qm", "init")
  170. out, err := exec.Command("git", "-C", root, "rev-parse", "--short", "HEAD").Output()
  171. if err != nil {
  172. t.Fatal(err)
  173. }
  174. return strings.TrimSpace(string(out))
  175. }
  176. // writeDeployScript crea deploy/update.sh en root (marca el layout como
  177. // git/rolling: el updater detecta que puede auto-aplicar).
  178. func writeDeployScript(t *testing.T, root string) {
  179. t.Helper()
  180. if err := os.MkdirAll(filepath.Join(root, "deploy"), 0o755); err != nil {
  181. t.Fatal(err)
  182. }
  183. if err := os.WriteFile(filepath.Join(root, "deploy", "update.sh"), []byte("#!/bin/bash\ntrue\n"), 0o755); err != nil {
  184. t.Fatal(err)
  185. }
  186. }
  187. func TestApplyYaEnCursoYScript(t *testing.T) {
  188. if !gitAvailable() {
  189. t.Skip("git no disponible")
  190. }
  191. root := t.TempDir()
  192. if err := os.MkdirAll(filepath.Join(root, "deploy"), 0o755); err != nil {
  193. t.Fatal(err)
  194. }
  195. script := "#!/bin/bash\necho STEP:backend\nsleep 0.1\necho STEP:done-steps\ntrue\n"
  196. if err := os.WriteFile(filepath.Join(root, "deploy", "update.sh"), []byte(script), 0o755); err != nil {
  197. t.Fatal(err)
  198. }
  199. u := New(root, "owner/netpulse", "", "2.0.0", nil)
  200. if !u.Apply() {
  201. t.Fatal("apply debería arrancar")
  202. }
  203. // Segundo apply concurrente → 409 already_updating
  204. if u.Apply() {
  205. t.Fatal("apply duplicado debería ser false")
  206. }
  207. deadline := time.Now().Add(30 * time.Second)
  208. for {
  209. st := u.Status()
  210. if m, ok := st.Updating.(progress); ok && m.Step == "done" {
  211. break
  212. }
  213. if time.Now().After(deadline) {
  214. t.Fatalf("timeout esperando done: %+v", st)
  215. }
  216. time.Sleep(50 * time.Millisecond)
  217. }
  218. st := u.Status()
  219. if st.LastLog == nil || *st.LastLog == "" {
  220. t.Fatalf("lastLog: %+v", st)
  221. }
  222. }
  223. func TestStableModeUpdateAvailable(t *testing.T) {
  224. withAPI(t, func(w http.ResponseWriter, r *http.Request) {
  225. // Compare del changelog (issue #490).
  226. if strings.Contains(r.URL.Path, "/compare/") {
  227. fmt.Fprint(w, `{"commits":[]}`)
  228. return
  229. }
  230. if r.URL.Path != "/repos/owner/netpulse/releases/latest" {
  231. t.Errorf("path: %s (modo estable debe consultar releases/latest)", r.URL.Path)
  232. }
  233. w.Header().Set("Content-Type", "application/json")
  234. fmt.Fprint(w, `{"tag_name":"v2.7.3","name":"v2.7.3"}`)
  235. })
  236. // Sin deploy/update.sh → modo estable. Versión embebida 2.7.2 < 2.7.3.
  237. u := New(t.TempDir(), "owner/netpulse", "", "2.7.2", nil)
  238. st := u.Check(context.Background())
  239. if st.Error != nil {
  240. t.Fatalf("error: %v", *st.Error)
  241. }
  242. if !st.UpdateAvailable {
  243. t.Fatal("debería haber update (2.7.2 < 2.7.3)")
  244. }
  245. if st.Latest == nil || *st.Latest != "v2.7.3" {
  246. t.Fatalf("latest: %v", st.Latest)
  247. }
  248. if st.Current != "2.7.2" {
  249. t.Fatalf("current: %s", st.Current)
  250. }
  251. if st.CanApply || st.Mode != "stable" {
  252. t.Fatalf("debería ser stable/!canApply: canApply=%v mode=%s", st.CanApply, st.Mode)
  253. }
  254. }
  255. func TestStableModeNoUpdateWhenSameVersion(t *testing.T) {
  256. withAPI(t, func(w http.ResponseWriter, r *http.Request) {
  257. fmt.Fprint(w, `{"tag_name":"v2.7.2","name":"v2.7.2"}`)
  258. })
  259. u := New(t.TempDir(), "owner/netpulse", "", "2.7.2", nil)
  260. st := u.Check(context.Background())
  261. if st.UpdateAvailable {
  262. t.Fatal("no debería haber update (misma versión)")
  263. }
  264. }
  265. func TestStableModeNoUpdateWhenOlder(t *testing.T) {
  266. withAPI(t, func(w http.ResponseWriter, r *http.Request) {
  267. fmt.Fprint(w, `{"tag_name":"v2.7.0","name":"v2.7.0"}`)
  268. })
  269. u := New(t.TempDir(), "owner/netpulse", "", "2.7.2", nil)
  270. st := u.Check(context.Background())
  271. if st.UpdateAvailable {
  272. t.Fatal("no debería haber update (2.7.0 < 2.7.2)")
  273. }
  274. }
  275. func TestCompareSemver(t *testing.T) {
  276. cases := []struct {
  277. a, b string
  278. want int
  279. }{
  280. {"2.7.2", "2.7.2", 0},
  281. {"v2.7.2", "2.7.2", 0},
  282. {"v2.7.3", "v2.7.2", 1},
  283. {"2.8.0", "2.7.9", 1},
  284. {"3.0.0", "2.9.9", 1},
  285. {"2.7.1", "2.7.2", -1},
  286. {"2.6.9", "2.7.0", -1},
  287. {"v2.7.2-rc1", "v2.7.2", 0}, // pre-release suffix descartado
  288. {"1.0.0", "1.0", 0}, // minor faltante = 0
  289. }
  290. for _, c := range cases {
  291. got := compareSemver(c.a, c.b)
  292. // normalizar a -1/0/1 para comparar
  293. if (c.want == 0 && got != 0) || (c.want > 0 && got <= 0) || (c.want < 0 && got >= 0) {
  294. t.Errorf("compareSemver(%q, %q) = %d, want sign %d", c.a, c.b, got, c.want)
  295. }
  296. }
  297. }
  298. func TestCanApplyDetection(t *testing.T) {
  299. // Sin deploy/update.sh → stable, !canApply
  300. u1 := New(t.TempDir(), "owner/netpulse", "", "1.0.0", nil)
  301. if u1.CanApply() || u1.mode != "stable" {
  302. t.Fatal("sin deploy/update.sh debería ser stable/!canApply")
  303. }
  304. // Con deploy/update.sh → rolling, canApply
  305. root := t.TempDir()
  306. writeDeployScript(t, root)
  307. u2 := New(root, "owner/netpulse", "", "1.0.0", nil)
  308. if !u2.CanApply() || u2.mode != "rolling" {
  309. t.Fatal("con deploy/update.sh debería ser rolling/canApply")
  310. }
  311. }
  312. // Issue #280: pesos por paso, PROGRESS explícito (clamp) y shape del status.
  313. func TestProgressWeightsAndClamp(t *testing.T) {
  314. u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", nil)
  315. pctOf := func() int {
  316. t.Helper()
  317. m, ok := u.Status().Updating.(progress)
  318. if !ok {
  319. t.Fatal("debería estar updating")
  320. }
  321. return m.Progress
  322. }
  323. u.appendLog("STEP:start\n", true)
  324. if p := pctOf(); p != stepWeight["start"] {
  325. t.Fatalf("start: %d", p)
  326. }
  327. u.appendLog("STEP:fetch\n", true)
  328. if p := pctOf(); p != stepWeight["fetch"] {
  329. t.Fatalf("fetch: %d", p)
  330. }
  331. u.appendLog("STEP:download\n", true)
  332. if p := pctOf(); p != stepWeight["download"] {
  333. t.Fatalf("download: %d", p)
  334. }
  335. // PROGRESS por debajo del peso del paso no retrocede.
  336. u.appendLog("PROGRESS:5\n", true)
  337. if p := pctOf(); p != stepWeight["download"] {
  338. t.Fatalf("progreso no puede bajar del peso: %d", p)
  339. }
  340. // PROGRESS dentro del paso avanza.
  341. u.appendLog("PROGRESS:55\n", true)
  342. if p := pctOf(); p != 55 {
  343. t.Fatalf("55: %d", p)
  344. }
  345. // PROGRESS absurdo se recorta a 99 (100 solo con done).
  346. u.appendLog("PROGRESS:150\n", true)
  347. if p := pctOf(); p != 99 {
  348. t.Fatalf("150 → 99: %d", p)
  349. }
  350. // done siempre 100.
  351. u.appendLog("STEP:done\n", true)
  352. if p := pctOf(); p != 100 {
  353. t.Fatalf("done: %d", p)
  354. }
  355. // Paso legado (script viejo) sin PROGRESS: peso por defecto del mapa.
  356. u.appendLog("STEP:binary\n", true)
  357. if p := pctOf(); p != stepWeight["binary"] {
  358. t.Fatalf("binary legado: %d", p)
  359. }
  360. }
  361. // Issue #280: el broadcaster notifica cambios de paso y el cancel retira.
  362. func TestSubscribeBroadcast(t *testing.T) {
  363. u := New(t.TempDir(), "owner/netpulse", "", "2.0.0", nil)
  364. ch, cancel := u.Subscribe()
  365. defer cancel()
  366. u.appendLog("STEP:download\n", true)
  367. select {
  368. case st := <-ch:
  369. m, ok := st.Updating.(progress)
  370. if !ok || m.Step != "download" || m.Progress != stepWeight["download"] {
  371. t.Fatalf("evento: %+v", st.Updating)
  372. }
  373. case <-time.After(2 * time.Second):
  374. t.Fatal("sin evento tras STEP")
  375. }
  376. // Un segundo evento (cambio de pct) y luego la baja no bloquea.
  377. u.appendLog("PROGRESS:50\n", true)
  378. select {
  379. case st := <-ch:
  380. m, _ := st.Updating.(progress)
  381. if m.Progress != 50 {
  382. t.Fatalf("progreso: %d", m.Progress)
  383. }
  384. case <-time.After(2 * time.Second):
  385. t.Fatal("sin evento tras PROGRESS")
  386. }
  387. cancel()
  388. // Tras cancel, broadcast no entrega ni bloquea.
  389. u.appendLog("STEP:verify\n", true)
  390. select {
  391. case <-ch:
  392. t.Fatal("no debería llegar tras cancel")
  393. default:
  394. }
  395. }
  396. func TestCheckSerializedUnderConcurrency(t *testing.T) {
  397. var inFlight, maxInFlight atomic.Int32
  398. withAPI(t, func(w http.ResponseWriter, r *http.Request) {
  399. switch {
  400. case r.URL.Path == "/repos/owner/netpulse/commits/main":
  401. n := inFlight.Add(1)
  402. for {
  403. m := maxInFlight.Load()
  404. if n <= m || maxInFlight.CompareAndSwap(m, n) {
  405. break
  406. }
  407. }
  408. defer inFlight.Add(-1)
  409. time.Sleep(50 * time.Millisecond)
  410. w.Header().Set("Content-Type", "application/json")
  411. fmt.Fprint(w, `{"sha":"abc1234deadbeef","commit":{"message":"feat: algo"}}`)
  412. case r.URL.Path == "/repos/owner/netpulse/releases/latest":
  413. w.Header().Set("Content-Type", "application/json")
  414. fmt.Fprint(w, `{"tag_name":"v2.5.0"}`)
  415. case r.URL.Path == "/repos/owner/netpulse/releases":
  416. w.Header().Set("Content-Type", "application/json")
  417. fmt.Fprint(w, `[]`)
  418. case strings.Contains(r.URL.Path, "/compare/"):
  419. w.Header().Set("Content-Type", "application/json")
  420. fmt.Fprint(w, `{"commits":[]}`)
  421. default:
  422. t.Errorf("path: %s", r.URL.Path)
  423. }
  424. })
  425. root := t.TempDir()
  426. writeDeployScript(t, root)
  427. writeGitHead(t, root)
  428. u := New(root, "owner/netpulse", "", "2.0.0", nil)
  429. var wg sync.WaitGroup
  430. for i := 0; i < 2; i++ {
  431. wg.Add(1)
  432. go func() {
  433. defer wg.Done()
  434. u.Check(context.Background())
  435. }()
  436. }
  437. wg.Wait()
  438. if got := maxInFlight.Load(); got != 1 {
  439. t.Fatalf("commits/main max in flight=%d want 1", got)
  440. }
  441. }