-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
722 lines (657 loc) · 21.4 KB
/
Copy pathmain_test.go
File metadata and controls
722 lines (657 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
func newTestApp(t *testing.T, handler http.HandlerFunc) (*App, *bytes.Buffer, *httptest.Server) {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
buf := &bytes.Buffer{}
app := &App{
Config: Config{
BaseURL: srv.URL,
APIKey: "test-key",
ProjectName: "test-project",
Version: "v1.0.0",
},
Client: srv.Client(),
Stdout: buf,
}
return app, buf, srv
}
func TestTrailingSlashStripped(t *testing.T) {
var gotPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[]`))
}))
t.Cleanup(srv.Close)
rawURL := srv.URL + "/"
app := &App{
Config: Config{
BaseURL: strings.TrimRight(rawURL, "/"),
APIKey: "k",
ProjectName: "p",
},
Client: srv.Client(),
Stdout: &bytes.Buffer{},
}
if _, err := app.getAllVersions(); err != nil {
t.Fatalf("getAllVersions: %v", err)
}
if gotPath != "/api/v1/project" {
t.Fatalf("expected request path /api/v1/project, got %q", gotPath)
}
}
func TestGetAllVersions_SinglePage(t *testing.T) {
projects := []Project{
{UUID: "u1", Name: "test-project", Version: "v1", LastBomImport: 2000},
{UUID: "u2", Name: "test-project", Version: "v2", LastBomImport: 1000},
}
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(projects)
})
got, err := app.getAllVersions()
if err != nil {
t.Fatalf("getAllVersions: %v", err)
}
if len(got) != 2 {
t.Fatalf("expected 2 projects, got %d", len(got))
}
if got[0].UUID != "u2" || got[1].UUID != "u1" {
t.Fatalf("expected sort by LastBomImport ascending; got order %s, %s", got[0].UUID, got[1].UUID)
}
}
func TestGetAllVersions_Pagination(t *testing.T) {
makePage := func(n int, prefix string) []Project {
out := make([]Project, n)
for i := 0; i < n; i++ {
out[i] = Project{UUID: fmt.Sprintf("%s-%d", prefix, i), Name: "test-project", Version: fmt.Sprintf("v%d", i)}
}
return out
}
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
page := r.URL.Query().Get("pageNumber")
w.Header().Set("Content-Type", "application/json")
switch page {
case "1":
_ = json.NewEncoder(w).Encode(makePage(50, "p1"))
case "2":
_ = json.NewEncoder(w).Encode(makePage(10, "p2"))
default:
_ = json.NewEncoder(w).Encode([]Project{})
}
})
got, err := app.getAllVersions()
if err != nil {
t.Fatalf("getAllVersions: %v", err)
}
if len(got) != 60 {
t.Fatalf("expected 60 projects, got %d", len(got))
}
}
func TestGetAllVersions_ServerError(t *testing.T) {
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "boom", http.StatusInternalServerError)
})
_, err := app.getAllVersions()
if err == nil {
t.Fatal("expected error")
}
msg := err.Error()
if !strings.Contains(msg, "500") {
t.Errorf("expected status 500 in error, got %q", msg)
}
if !strings.Contains(msg, "boom") {
t.Errorf("expected body 'boom' in error, got %q", msg)
}
}
func TestGetAllVersions_HTMLResponse(t *testing.T) {
htmlBody := `<html><head><title>302 Found</title></head><body>Found. Redirecting to /login</body></html>`
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(htmlBody))
})
_, err := app.getAllVersions()
if err == nil {
t.Fatal("expected error from HTML response")
}
msg := err.Error()
if !strings.Contains(msg, "302 Found") && !strings.Contains(msg, "<html>") {
t.Errorf("expected body preview in error, got: %q", msg)
}
if !strings.Contains(msg, "preview") {
t.Errorf("expected 'preview' label in error, got: %q", msg)
}
}
type patchRecord struct {
uuid string
payload map[string]interface{}
}
func newPatchRecorder() (http.HandlerFunc, *[]patchRecord, *sync.Mutex) {
var records []patchRecord
var mu sync.Mutex
handler := func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPatch {
http.Error(w, "unexpected method", http.StatusBadRequest)
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/api/v1/project/"), "/")
uuid := parts[0]
var payload map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
mu.Lock()
records = append(records, patchRecord{uuid: uuid, payload: payload})
mu.Unlock()
w.WriteHeader(http.StatusOK)
}
return handler, &records, &mu
}
func cleanTestProjects() []Project {
return []Project{
{UUID: "u-target", Name: "test-project", Version: "v1.0.0", Active: false, IsLatest: false},
{UUID: "u-old1", Name: "test-project", Version: "v0.9.0", Active: true, IsLatest: false},
{UUID: "u-old2", Name: "test-project", Version: "v0.8.0", Active: false, IsLatest: false},
}
}
func TestUpdateLifecycle_Clean(t *testing.T) {
handler, records, mu := newPatchRecorder()
app, _, _ := newTestApp(t, handler)
app.updateLifecycle(cleanTestProjects(), false, true)
mu.Lock()
defer mu.Unlock()
if len(*records) != 2 {
t.Fatalf("expected 2 patches, got %d: %+v", len(*records), *records)
}
byUUID := map[string]map[string]interface{}{}
for _, r := range *records {
byUUID[r.uuid] = r.payload
}
if v, ok := byUUID["u-target"]["active"]; !ok || v != true {
t.Errorf("expected u-target active=true, got %+v", byUUID["u-target"])
}
if v, ok := byUUID["u-old1"]["active"]; !ok || v != false {
t.Errorf("expected u-old1 active=false, got %+v", byUUID["u-old1"])
}
if _, patched := byUUID["u-old2"]; patched {
t.Errorf("u-old2 already had active=false; should not be patched")
}
}
func TestUpdateLifecycle_Latest(t *testing.T) {
handler, records, mu := newPatchRecorder()
app, _, _ := newTestApp(t, handler)
projects := []Project{
{UUID: "u-target", Name: "test-project", Version: "v1.0.0", Active: true, IsLatest: false},
{UUID: "u-old1", Name: "test-project", Version: "v0.9.0", Active: true, IsLatest: true},
{UUID: "u-old2", Name: "test-project", Version: "v0.8.0", Active: true, IsLatest: false},
}
app.updateLifecycle(projects, true, false)
mu.Lock()
defer mu.Unlock()
if len(*records) != 2 {
t.Fatalf("expected 2 patches, got %d: %+v", len(*records), *records)
}
byUUID := map[string]map[string]interface{}{}
for _, r := range *records {
byUUID[r.uuid] = r.payload
}
if v, ok := byUUID["u-target"]["isLatest"]; !ok || v != true {
t.Errorf("expected u-target isLatest=true, got %+v", byUUID["u-target"])
}
if v, ok := byUUID["u-old1"]["isLatest"]; !ok || v != false {
t.Errorf("expected u-old1 isLatest=false, got %+v", byUUID["u-old1"])
}
if _, patched := byUUID["u-old2"]; patched {
t.Errorf("u-old2 already had isLatest=false; should not be patched")
}
}
func TestUpdateLifecycle_Both(t *testing.T) {
handler, records, mu := newPatchRecorder()
app, _, _ := newTestApp(t, handler)
projects := []Project{
{UUID: "u-target", Name: "test-project", Version: "v1.0.0", Active: false, IsLatest: false},
{UUID: "u-old1", Name: "test-project", Version: "v0.9.0", Active: true, IsLatest: true},
}
app.updateLifecycle(projects, true, true)
mu.Lock()
defer mu.Unlock()
if len(*records) != 2 {
t.Fatalf("expected 2 patches, got %d: %+v", len(*records), *records)
}
byUUID := map[string]map[string]interface{}{}
for _, r := range *records {
byUUID[r.uuid] = r.payload
}
target := byUUID["u-target"]
if target["active"] != true || target["isLatest"] != true {
t.Errorf("expected target active=true, isLatest=true; got %+v", target)
}
old := byUUID["u-old1"]
if old["active"] != false || old["isLatest"] != false {
t.Errorf("expected old1 active=false, isLatest=false; got %+v", old)
}
}
func TestUploadSBOM(t *testing.T) {
dir := t.TempDir()
sbomPath := filepath.Join(dir, "sbom.json")
sbomContent := []byte(`{"bomFormat":"CycloneDX"}`)
if err := os.WriteFile(sbomPath, sbomContent, 0o600); err != nil {
t.Fatal(err)
}
var (
gotPath string
gotProjectName string
gotVersion string
gotAutoCreate string
gotFileContent []byte
)
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
ct := r.Header.Get("Content-Type")
_, params, err := mime.ParseMediaType(ct)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
mr := multipart.NewReader(r.Body, params["boundary"])
for {
p, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
switch p.FormName() {
case "projectName":
b, _ := io.ReadAll(p)
gotProjectName = string(b)
case "projectVersion":
b, _ := io.ReadAll(p)
gotVersion = string(b)
case "autoCreate":
b, _ := io.ReadAll(p)
gotAutoCreate = string(b)
case "bom":
gotFileContent, _ = io.ReadAll(p)
}
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"token":"abc"}`))
})
app.Config.SbomFile = sbomPath
if err := app.uploadSBOM(); err != nil {
t.Fatalf("uploadSBOM: %v", err)
}
if gotPath != "/api/v1/bom" {
t.Errorf("expected POST to /api/v1/bom, got %s", gotPath)
}
if gotProjectName != "test-project" {
t.Errorf("projectName: got %q", gotProjectName)
}
if gotVersion != "v1.0.0" {
t.Errorf("projectVersion: got %q", gotVersion)
}
if gotAutoCreate != "true" {
t.Errorf("autoCreate: got %q", gotAutoCreate)
}
if !bytes.Equal(gotFileContent, sbomContent) {
t.Errorf("bom file content mismatch")
}
}
func TestVerboseOutput(t *testing.T) {
app, buf, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[]`))
})
app.Config.Verbose = true
if _, err := app.getAllVersions(); err != nil {
t.Fatalf("getAllVersions: %v", err)
}
out := buf.String()
if !strings.Contains(out, "[verbose] →") {
t.Errorf("expected '[verbose] →' in output, got: %s", out)
}
if !strings.Contains(out, "[verbose] ←") {
t.Errorf("expected '[verbose] ←' in output, got: %s", out)
}
if !strings.Contains(out, "GET") {
t.Errorf("expected method GET in output, got: %s", out)
}
if !strings.Contains(out, "200 OK") {
t.Errorf("expected '200 OK' status in output, got: %s", out)
}
}
func TestVerboseOff(t *testing.T) {
app, buf, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[]`))
})
if _, err := app.getAllVersions(); err != nil {
t.Fatalf("getAllVersions: %v", err)
}
if strings.Contains(buf.String(), "[verbose]") {
t.Errorf("expected no [verbose] output when Verbose=false; got: %s", buf.String())
}
}
func TestDisplayVersions(t *testing.T) {
app, buf, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {})
projects := []Project{
{UUID: "u-1", Name: "test-project", Version: "v1.0.0", Active: true, IsLatest: true, LastBomImport: 1700000000000},
{UUID: "u-2", Name: "other-project", Version: "v9.9.9", Active: true, IsLatest: false},
}
app.displayVersions(projects)
out := buf.String()
for _, want := range []string{"VERSION", "ACTIVE", "LATEST", "LAST UPLOAD", "UUID", "v1.0.0", "u-1"} {
if !strings.Contains(out, want) {
t.Errorf("expected %q in output, got: %s", want, out)
}
}
if strings.Contains(out, "other-project") || strings.Contains(out, "v9.9.9") {
t.Errorf("expected projects with different name to be filtered out; got: %s", out)
}
}
func TestValidateVersionExists_Found(t *testing.T) {
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {})
projects := []Project{
{Name: "test-project", Version: "v0.9.0"},
{Name: "test-project", Version: "v1.0.0"},
}
if err := app.validateVersionExists(projects, "v1.0.0"); err != nil {
t.Fatalf("expected nil error, got %v", err)
}
}
func TestValidateVersionExists_NotFound(t *testing.T) {
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {})
projects := []Project{
{Name: "test-project", Version: "v1.5.7"},
{Name: "test-project", Version: "v1.5.8"},
}
err := app.validateVersionExists(projects, "1.5.8")
if err == nil {
t.Fatal("expected error for missing version")
}
msg := err.Error()
if !strings.Contains(msg, `"1.5.8"`) {
t.Errorf("expected requested version %q in error, got: %s", "1.5.8", msg)
}
if !strings.Contains(msg, "not found") {
t.Errorf("expected 'not found' in error, got: %s", msg)
}
if !strings.Contains(msg, "v1.5.8") {
t.Errorf("expected available version 'v1.5.8' in error to make typo obvious, got: %s", msg)
}
}
func TestValidateVersionExists_IgnoresOtherProjects(t *testing.T) {
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {})
projects := []Project{
{Name: "other-project", Version: "v1.0.0"},
}
err := app.validateVersionExists(projects, "v1.0.0")
if err == nil {
t.Fatal("expected error: matching version under a different project name should not satisfy validation")
}
if !strings.Contains(err.Error(), "test-project") {
t.Errorf("expected configured project name in error, got: %s", err.Error())
}
}
func TestUpdateLifecycle_VersionNotInList(t *testing.T) {
projects := []Project{
{UUID: "u-1", Name: "test-project", Version: "v1.5.7", Active: true, IsLatest: false},
{UUID: "u-2", Name: "test-project", Version: "v1.5.8", Active: true, IsLatest: true},
}
{
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
t.Fatalf("validation phase must not send any HTTP requests; got %s %s", r.Method, r.URL.Path)
})
app.Config.Version = "1.5.8"
if err := app.validateVersionExists(projects, app.Config.Version); err == nil {
t.Fatal("expected validateVersionExists to reject typo'd version")
}
}
handler, records, mu := newPatchRecorder()
app, _, _ := newTestApp(t, handler)
app.Config.Version = "1.5.8"
app.updateLifecycle(projects, true, true)
mu.Lock()
defer mu.Unlock()
if len(*records) != 2 {
t.Fatalf("expected 2 destructive PATCHes (one per project) when validation is bypassed; got %d: %+v",
len(*records), *records)
}
for _, r := range *records {
if r.payload["active"] != false {
t.Errorf("expected active=false in destructive PATCH for %s, got %+v", r.uuid, r.payload)
}
if r.payload["isLatest"] != false && r.uuid == "u-2" {
t.Errorf("expected isLatest=false in destructive PATCH for %s, got %+v", r.uuid, r.payload)
}
}
}
func TestResolveProjectUUID(t *testing.T) {
const uuid = "abc-123-def"
want := Project{UUID: uuid, Name: "My-Web-App", Version: "v2.1.0", Active: true, IsLatest: true}
var gotPath string
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(want)
})
got, err := app.resolveProjectUUID(uuid)
if err != nil {
t.Fatalf("resolveProjectUUID: %v", err)
}
if gotPath != "/api/v1/project/"+uuid {
t.Errorf("expected GET /api/v1/project/%s, got %s", uuid, gotPath)
}
if got.Name != "My-Web-App" || got.Version != "v2.1.0" || got.UUID != uuid {
t.Errorf("unexpected resolved project: %+v", got)
}
}
func TestResolveProjectUUID_NotFound(t *testing.T) {
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "project could not be found", http.StatusNotFound)
})
_, err := app.resolveProjectUUID("does-not-exist")
if err == nil {
t.Fatal("expected error for 404 response")
}
if !strings.Contains(err.Error(), "404") {
t.Errorf("expected status 404 in error, got %q", err.Error())
}
}
func TestUploadSBOM_ByUUID(t *testing.T) {
dir := t.TempDir()
sbomPath := filepath.Join(dir, "sbom.json")
sbomContent := []byte(`{"bomFormat":"CycloneDX"}`)
if err := os.WriteFile(sbomPath, sbomContent, 0o600); err != nil {
t.Fatal(err)
}
const uuid = "abc-123-def"
var (
gotPath string
gotProject string
gotFileContent []byte
sawNameField bool
sawVersionField bool
sawAutoCreate bool
)
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
_, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
mr := multipart.NewReader(r.Body, params["boundary"])
for {
p, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
switch p.FormName() {
case "project":
b, _ := io.ReadAll(p)
gotProject = string(b)
case "projectName":
sawNameField = true
case "projectVersion":
sawVersionField = true
case "autoCreate":
sawAutoCreate = true
case "bom":
gotFileContent, _ = io.ReadAll(p)
}
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"token":"abc"}`))
})
app.Config.SbomFile = sbomPath
app.Config.ProjectUUID = uuid
// UUID-only mode: name/version are not set.
app.Config.ProjectName = ""
app.Config.Version = ""
if err := app.uploadSBOM(); err != nil {
t.Fatalf("uploadSBOM: %v", err)
}
if gotPath != "/api/v1/bom" {
t.Errorf("expected POST to /api/v1/bom, got %s", gotPath)
}
if gotProject != uuid {
t.Errorf("expected project=%q in multipart body, got %q", uuid, gotProject)
}
if sawNameField || sawVersionField || sawAutoCreate {
t.Errorf("UUID upload must not send projectName/projectVersion/autoCreate (name=%v version=%v autoCreate=%v)",
sawNameField, sawVersionField, sawAutoCreate)
}
if !bytes.Equal(gotFileContent, sbomContent) {
t.Errorf("bom file content mismatch")
}
}
func TestUpdateLifecycle_ByUUID(t *testing.T) {
const targetUUID = "u-target"
resolved := Project{UUID: targetUUID, Name: "test-project", Version: "v1.0.0", Active: false, IsLatest: false}
siblings := []Project{
{UUID: targetUUID, Name: "test-project", Version: "v1.0.0", Active: false, IsLatest: false},
{UUID: "u-old1", Name: "test-project", Version: "v0.9.0", Active: true, IsLatest: true},
}
var (
mu sync.Mutex
resolveHit int
listHit int
patches []patchRecord
)
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/project/"+targetUUID:
mu.Lock()
resolveHit++
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(resolved)
case r.Method == http.MethodGet && r.URL.Path == "/api/v1/project":
mu.Lock()
listHit++
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(siblings)
case r.Method == http.MethodPatch:
uuid := strings.TrimPrefix(r.URL.Path, "/api/v1/project/")
var payload map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
mu.Lock()
patches = append(patches, patchRecord{uuid: uuid, payload: payload})
mu.Unlock()
w.WriteHeader(http.StatusOK)
default:
http.Error(w, "unexpected "+r.Method+" "+r.URL.Path, http.StatusBadRequest)
}
})
// Simulate UUID mode: only the UUID is known up front.
app.Config.ProjectName = ""
app.Config.Version = ""
app.Config.ProjectUUID = targetUUID
// Drive the real production code paths (the same methods main() calls) so
// this test tracks any change to the resolve -> list -> patch orchestration.
if err := app.resolveIfUUID(); err != nil {
t.Fatalf("resolveIfUUID: %v", err)
}
if err := app.runLifecycle(false, true, true); err != nil {
t.Fatalf("runLifecycle: %v", err)
}
mu.Lock()
defer mu.Unlock()
if resolveHit != 1 {
t.Errorf("expected exactly 1 resolve call, got %d", resolveHit)
}
if listHit < 1 {
t.Errorf("expected at least 1 list call, got %d", listHit)
}
// Exactly the target and its one stale sibling should be patched — no
// collateral PATCH to any other project sharing the resolved name.
if len(patches) != 2 {
t.Fatalf("expected exactly 2 patches, got %d: %+v", len(patches), patches)
}
byUUID := map[string]map[string]interface{}{}
for _, p := range patches {
byUUID[p.uuid] = p.payload
}
if byUUID[targetUUID]["active"] != true || byUUID[targetUUID]["isLatest"] != true {
t.Errorf("expected target %s active=true,isLatest=true; got %+v", targetUUID, byUUID[targetUUID])
}
if byUUID["u-old1"]["active"] != false || byUUID["u-old1"]["isLatest"] != false {
t.Errorf("expected u-old1 active=false,isLatest=false; got %+v", byUUID["u-old1"])
}
}
func TestUpdateLifecycle_PatchErrorPropagates(t *testing.T) {
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "boom", http.StatusInternalServerError)
})
err := app.updateLifecycle(cleanTestProjects(), false, true)
if err == nil {
t.Fatal("expected updateLifecycle to return an error when a PATCH fails")
}
if !strings.Contains(err.Error(), "failed to patch") {
t.Errorf("expected 'failed to patch' in error, got: %v", err)
}
}
func TestResolveIfUUID_EmptyName(t *testing.T) {
app, _, _ := newTestApp(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{}`))
})
app.Config.ProjectUUID = "some-uuid"
err := app.resolveIfUUID()
if err == nil {
t.Fatal("expected error when the resolved project has an empty name")
}
if !strings.Contains(err.Error(), "empty name") {
t.Errorf("expected 'empty name' in error, got: %v", err)
}
}