-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstance_group_test.go
More file actions
715 lines (634 loc) · 24.2 KB
/
Copy pathinstance_group_test.go
File metadata and controls
715 lines (634 loc) · 24.2 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
package main
import (
"context"
"errors"
"strings"
"sync"
"testing"
upcloud "github.com/UpCloudLtd/upcloud-go-api/v8/upcloud"
"github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/client"
"github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/request"
"github.com/hashicorp/go-hclog"
"gitlab.com/gitlab-org/fleeting/fleeting/provider"
)
// ─── mock ────────────────────────────────────────────────────────────────────
// mockSvc is a test double for upcloudSvc.
// Each field is a function so individual tests can customise behaviour.
type mockSvc struct {
mu sync.Mutex
getAccount func(context.Context) (*upcloud.Account, error)
getServersWithFilters func(context.Context, *request.GetServersWithFiltersRequest) (*upcloud.Servers, error)
createServer func(context.Context, *request.CreateServerRequest) (*upcloud.ServerDetails, error)
stopServer func(context.Context, *request.StopServerRequest) (*upcloud.ServerDetails, error)
waitForServerState func(context.Context, *request.WaitForServerStateRequest) (*upcloud.ServerDetails, error)
deleteServerAndStorages func(context.Context, *request.DeleteServerAndStoragesRequest) error
getServerDetails func(context.Context, *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error)
}
func (m *mockSvc) GetAccount(ctx context.Context) (*upcloud.Account, error) {
return m.getAccount(ctx)
}
func (m *mockSvc) GetServersWithFilters(ctx context.Context, r *request.GetServersWithFiltersRequest) (*upcloud.Servers, error) {
return m.getServersWithFilters(ctx, r)
}
func (m *mockSvc) CreateServer(ctx context.Context, r *request.CreateServerRequest) (*upcloud.ServerDetails, error) {
m.mu.Lock()
defer m.mu.Unlock()
return m.createServer(ctx, r)
}
func (m *mockSvc) StopServer(ctx context.Context, r *request.StopServerRequest) (*upcloud.ServerDetails, error) {
m.mu.Lock()
defer m.mu.Unlock()
return m.stopServer(ctx, r)
}
func (m *mockSvc) WaitForServerState(ctx context.Context, r *request.WaitForServerStateRequest) (*upcloud.ServerDetails, error) {
m.mu.Lock()
defer m.mu.Unlock()
return m.waitForServerState(ctx, r)
}
func (m *mockSvc) DeleteServerAndStorages(ctx context.Context, r *request.DeleteServerAndStoragesRequest) error {
m.mu.Lock()
defer m.mu.Unlock()
return m.deleteServerAndStorages(ctx, r)
}
func (m *mockSvc) GetServerDetails(ctx context.Context, r *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error) {
return m.getServerDetails(ctx, r)
}
// newMockSvc returns a mock where every method panics unless overridden.
func newMockSvc() *mockSvc {
panic := func(name string) { panic("unexpected call to mockSvc." + name) }
return &mockSvc{
getAccount: func(context.Context) (*upcloud.Account, error) { panic("GetAccount"); return nil, nil },
getServersWithFilters: func(context.Context, *request.GetServersWithFiltersRequest) (*upcloud.Servers, error) {
panic("GetServersWithFilters")
return nil, nil
},
createServer: func(context.Context, *request.CreateServerRequest) (*upcloud.ServerDetails, error) {
panic("CreateServer")
return nil, nil
},
stopServer: func(context.Context, *request.StopServerRequest) (*upcloud.ServerDetails, error) {
panic("StopServer")
return nil, nil
},
waitForServerState: func(context.Context, *request.WaitForServerStateRequest) (*upcloud.ServerDetails, error) {
panic("WaitForServerState")
return nil, nil
},
deleteServerAndStorages: func(context.Context, *request.DeleteServerAndStoragesRequest) error {
panic("DeleteServerAndStorages")
return nil
},
getServerDetails: func(context.Context, *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error) {
panic("GetServerDetails")
return nil, nil
},
}
}
// baseGroup returns a minimal valid InstanceGroup with a pre-set mock service.
func baseGroup(svc *mockSvc) *InstanceGroup {
g := &InstanceGroup{
Token: "test-token",
Zone: "fi-hel1",
Template: "template-uuid",
Name: "test-group",
Plan: defaultPlan,
svc: svc,
log: hclog.NewNullLogger(),
}
return g
}
// ─── validate ────────────────────────────────────────────────────────────────
func TestValidate(t *testing.T) {
tests := []struct {
name string
g InstanceGroup
wantErr bool
wantPlan string
wantPrefix string
wantTitlePrefix string
wantMaxSize int
}{
{
name: "token auth - all required fields",
g: InstanceGroup{Token: "tok", Zone: "z", Template: "t", Name: "n"},
wantPlan: defaultPlan,
wantPrefix: defaultNamePrefix,
wantTitlePrefix: defaultTitlePrefix,
wantMaxSize: defaultMaxSize,
},
{
name: "username+password auth",
g: InstanceGroup{Username: "u", Password: "p", Zone: "z", Template: "t", Name: "n"},
},
{
name: "no auth at all",
g: InstanceGroup{Zone: "z", Template: "t", Name: "n"},
wantErr: true,
},
{
name: "username without password",
g: InstanceGroup{Username: "u", Zone: "z", Template: "t", Name: "n"},
wantErr: true,
},
{
name: "password without username",
g: InstanceGroup{Password: "p", Zone: "z", Template: "t", Name: "n"},
wantErr: true,
},
{
name: "missing zone",
g: InstanceGroup{Token: "tok", Template: "t", Name: "n"},
wantErr: true,
},
{
name: "missing template",
g: InstanceGroup{Token: "tok", Zone: "z", Name: "n"},
wantErr: true,
},
{
name: "missing name",
g: InstanceGroup{Token: "tok", Zone: "z", Template: "t"},
wantErr: true,
},
{
name: "explicit plan preserved",
g: InstanceGroup{Token: "tok", Zone: "z", Template: "t", Name: "n", Plan: "2xCPU-4GB"},
wantPlan: "2xCPU-4GB",
wantMaxSize: defaultMaxSize,
},
{
name: "explicit name prefix preserved",
g: InstanceGroup{Token: "tok", Zone: "z", Template: "t", Name: "n", NamePrefix: "ci"},
wantPlan: defaultPlan,
wantPrefix: "ci",
wantMaxSize: defaultMaxSize,
},
{
name: "explicit title prefix preserved",
g: InstanceGroup{Token: "tok", Zone: "z", Template: "t", Name: "n", TitlePrefix: "ci-runner"},
wantPlan: defaultPlan,
wantTitlePrefix: "ci-runner",
wantMaxSize: defaultMaxSize,
},
{
name: "explicit max size preserved",
g: InstanceGroup{Token: "tok", Zone: "z", Template: "t", Name: "n", MaxSize: 5},
wantPlan: defaultPlan,
wantMaxSize: 5,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := tc.g.validate()
if (err != nil) != tc.wantErr {
t.Fatalf("validate() error = %v, wantErr = %v", err, tc.wantErr)
}
if tc.wantErr {
return
}
if tc.wantPlan != "" && tc.g.Plan != tc.wantPlan {
t.Errorf("Plan = %q, want %q", tc.g.Plan, tc.wantPlan)
}
if tc.wantPrefix != "" && tc.g.NamePrefix != tc.wantPrefix {
t.Errorf("NamePrefix = %q, want %q", tc.g.NamePrefix, tc.wantPrefix)
}
if tc.wantTitlePrefix != "" && tc.g.TitlePrefix != tc.wantTitlePrefix {
t.Errorf("TitlePrefix = %q, want %q", tc.g.TitlePrefix, tc.wantTitlePrefix)
}
if tc.wantMaxSize != 0 && tc.g.MaxSize != tc.wantMaxSize {
t.Errorf("MaxSize = %d, want %d", tc.g.MaxSize, tc.wantMaxSize)
}
})
}
}
// ─── mapServerState ───────────────────────────────────────────────────────────
func TestMapServerState(t *testing.T) {
tests := []struct {
state string
want provider.State
}{
{upcloud.ServerStateStarted, provider.StateRunning},
{upcloud.ServerStateStopped, provider.StateDeleted},
{upcloud.ServerStateError, provider.StateDeleted},
{"maintenance", provider.StateCreating},
{"new", provider.StateCreating},
{"", provider.StateCreating},
}
for _, tc := range tests {
t.Run(tc.state, func(t *testing.T) {
got := mapServerState(tc.state)
if got != tc.want {
t.Errorf("mapServerState(%q) = %v, want %v", tc.state, got, tc.want)
}
})
}
}
// ─── randomSuffix ─────────────────────────────────────────────────────────────
func TestRandomSuffix(t *testing.T) {
const allowed = "abcdefghijklmnopqrstuvwxyz0123456789"
for _, n := range []int{0, 1, 8, 16} {
s := randomSuffix(n)
if len(s) != n {
t.Errorf("randomSuffix(%d): len = %d, want %d", n, len(s), n)
}
for _, c := range s {
if !strings.ContainsRune(allowed, c) {
t.Errorf("randomSuffix(%d): unexpected character %q in %q", n, c, s)
}
}
}
// Two calls should almost always differ (birthday problem: 36^8 possibilities).
if a, b := randomSuffix(8), randomSuffix(8); a == b {
t.Logf("randomSuffix returned identical values twice (%q) — unlikely but not impossible", a)
}
}
// ─── sanitizeNamePrefix ─────────────────────────────────────────────────────────
func TestSanitizeNamePrefix(t *testing.T) {
cases := []struct {
in, want string
}{
{"fleeting", "fleeting"},
{"CI", "ci"},
{"GitLab", "gitlab"},
{"My_Runner", "my-runner"},
{"My_Runner!", "my-runner"},
{"--ci--", "ci"},
{"a..b", "a-b"},
{" spaced ", "spaced"},
{"___", ""},
{"", ""},
// 60 chars → truncated to 54 so "<prefix>-<8 char suffix>" fits a 63-char label
{strings.Repeat("a", 60), strings.Repeat("a", 54)},
// truncation must not leave a trailing hyphen
{strings.Repeat("a", 53) + "--bb", strings.Repeat("a", 53)},
}
for _, c := range cases {
if got := sanitizeNamePrefix(c.in); got != c.want {
t.Errorf("sanitizeNamePrefix(%q) = %q, want %q", c.in, got, c.want)
}
}
}
// ─── Update ───────────────────────────────────────────────────────────────────
func TestUpdate(t *testing.T) {
mock := newMockSvc()
mock.getServersWithFilters = func(_ context.Context, _ *request.GetServersWithFiltersRequest) (*upcloud.Servers, error) {
return &upcloud.Servers{
Servers: []upcloud.Server{
{UUID: "uuid-1", State: upcloud.ServerStateStarted},
{UUID: "uuid-2", State: upcloud.ServerStateStopped},
},
}, nil
}
g := baseGroup(mock)
seen := map[string]provider.State{}
err := g.Update(context.Background(), func(id string, state provider.State) {
seen[id] = state
})
if err != nil {
t.Fatalf("Update() unexpected error: %v", err)
}
if len(seen) != 2 {
t.Fatalf("Update() reported %d instances, want 2", len(seen))
}
if seen["uuid-1"] != provider.StateRunning {
t.Errorf("uuid-1 state = %v, want StateRunning", seen["uuid-1"])
}
if seen["uuid-2"] != provider.StateDeleted {
t.Errorf("uuid-2 state = %v, want StateDeleted", seen["uuid-2"])
}
}
func TestUpdate_APIError(t *testing.T) {
mock := newMockSvc()
mock.getServersWithFilters = func(_ context.Context, _ *request.GetServersWithFiltersRequest) (*upcloud.Servers, error) {
return nil, errors.New("api error")
}
g := baseGroup(mock)
if err := g.Update(context.Background(), func(string, provider.State) {}); err == nil {
t.Fatal("Update() expected error, got nil")
}
}
// ─── Increase ─────────────────────────────────────────────────────────────────
func TestIncrease_AllSucceed(t *testing.T) {
var created []string
mock := newMockSvc()
mock.createServer = func(_ context.Context, r *request.CreateServerRequest) (*upcloud.ServerDetails, error) {
created = append(created, r.Hostname)
return &upcloud.ServerDetails{}, nil
}
g := baseGroup(mock)
n, err := g.Increase(context.Background(), 3)
if err != nil {
t.Fatalf("Increase() unexpected error: %v", err)
}
if n != 3 {
t.Errorf("Increase() = %d, want 3", n)
}
if len(created) != 3 {
t.Errorf("CreateServer called %d times, want 3", len(created))
}
}
func TestIncrease_PartialFailure(t *testing.T) {
calls := 0
mock := newMockSvc()
mock.createServer = func(_ context.Context, _ *request.CreateServerRequest) (*upcloud.ServerDetails, error) {
calls++
if calls%2 == 0 {
return nil, errors.New("quota exceeded")
}
return &upcloud.ServerDetails{}, nil
}
g := baseGroup(mock)
n, err := g.Increase(context.Background(), 4)
// Failures are aggregated into the returned error so the taskscaler can back off.
if err == nil {
t.Fatal("Increase() expected error for partial failure, got nil")
}
if n != 2 {
t.Errorf("Increase() = %d, want 2 (half succeed)", n)
}
}
func TestIncrease_AllFail(t *testing.T) {
mock := newMockSvc()
mock.createServer = func(_ context.Context, _ *request.CreateServerRequest) (*upcloud.ServerDetails, error) {
return nil, errors.New("HOSTNAME_INVALID")
}
g := baseGroup(mock)
n, err := g.Increase(context.Background(), 2)
if err == nil {
t.Fatal("Increase() expected error when all creates fail, got nil")
}
if !strings.Contains(err.Error(), "HOSTNAME_INVALID") {
t.Errorf("Increase() error = %v, want it to wrap the API error", err)
}
if n != 0 {
t.Errorf("Increase() = %d, want 0", n)
}
}
func TestIncrease_Zero(t *testing.T) {
g := baseGroup(newMockSvc())
n, err := g.Increase(context.Background(), 0)
if err != nil || n != 0 {
t.Errorf("Increase(0) = (%d, %v), want (0, nil)", n, err)
}
}
func TestIncrease_SetsUserData(t *testing.T) {
var got string
mock := newMockSvc()
mock.createServer = func(_ context.Context, r *request.CreateServerRequest) (*upcloud.ServerDetails, error) {
got = r.UserData
return &upcloud.ServerDetails{}, nil
}
g := baseGroup(mock)
g.UserData = "https://example.com/init.sh"
g.Increase(context.Background(), 1)
if got != g.UserData {
t.Errorf("CreateServer UserData = %q, want %q", got, g.UserData)
}
}
// ─── Decrease ─────────────────────────────────────────────────────────────────
// startedDetails returns server details in the "started" state, as
// stopAndDelete checks current state before stopping.
func startedDetails(context.Context, *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error) {
return &upcloud.ServerDetails{Server: upcloud.Server{State: upcloud.ServerStateStarted}}, nil
}
func TestDecrease_AllSucceed(t *testing.T) {
mock := newMockSvc()
mock.getServerDetails = startedDetails
mock.stopServer = func(_ context.Context, _ *request.StopServerRequest) (*upcloud.ServerDetails, error) {
return &upcloud.ServerDetails{}, nil
}
mock.waitForServerState = func(_ context.Context, _ *request.WaitForServerStateRequest) (*upcloud.ServerDetails, error) {
return &upcloud.ServerDetails{}, nil
}
mock.deleteServerAndStorages = func(_ context.Context, _ *request.DeleteServerAndStoragesRequest) error {
return nil
}
g := baseGroup(mock)
instances := []string{"uuid-1", "uuid-2", "uuid-3"}
succeeded, err := g.Decrease(context.Background(), instances)
if err != nil {
t.Fatalf("Decrease() unexpected error: %v", err)
}
if len(succeeded) != 3 {
t.Errorf("Decrease() succeeded = %d, want 3", len(succeeded))
}
}
func TestDecrease_PartialFailure(t *testing.T) {
mock := newMockSvc()
mock.getServerDetails = startedDetails
mock.stopServer = func(_ context.Context, r *request.StopServerRequest) (*upcloud.ServerDetails, error) {
if r.UUID == "uuid-bad" {
return nil, errors.New("stop failed")
}
return &upcloud.ServerDetails{}, nil
}
mock.waitForServerState = func(_ context.Context, _ *request.WaitForServerStateRequest) (*upcloud.ServerDetails, error) {
return &upcloud.ServerDetails{}, nil
}
mock.deleteServerAndStorages = func(_ context.Context, _ *request.DeleteServerAndStoragesRequest) error {
return nil
}
g := baseGroup(mock)
succeeded, err := g.Decrease(context.Background(), []string{"uuid-ok", "uuid-bad"})
if err == nil {
t.Fatal("Decrease() expected error for partial failure, got nil")
}
if len(succeeded) != 1 || succeeded[0] != "uuid-ok" {
t.Errorf("Decrease() succeeded = %v, want [uuid-ok]", succeeded)
}
}
func TestDecrease_AlreadyStopped(t *testing.T) {
deleted := false
mock := newMockSvc()
mock.getServerDetails = func(_ context.Context, _ *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error) {
return &upcloud.ServerDetails{Server: upcloud.Server{State: upcloud.ServerStateStopped}}, nil
}
// stopServer and waitForServerState intentionally left as panics:
// an already-stopped server must be deleted without a stop attempt.
mock.deleteServerAndStorages = func(_ context.Context, _ *request.DeleteServerAndStoragesRequest) error {
deleted = true
return nil
}
g := baseGroup(mock)
succeeded, err := g.Decrease(context.Background(), []string{"uuid-stopped"})
if err != nil {
t.Fatalf("Decrease() unexpected error: %v", err)
}
if !deleted {
t.Error("Decrease() did not delete the already-stopped server")
}
if len(succeeded) != 1 {
t.Errorf("Decrease() succeeded = %v, want [uuid-stopped]", succeeded)
}
}
func TestDecrease_Empty(t *testing.T) {
g := baseGroup(newMockSvc())
succeeded, err := g.Decrease(context.Background(), nil)
if err != nil || len(succeeded) != 0 {
t.Errorf("Decrease(nil) = (%v, %v), want ([], nil)", succeeded, err)
}
}
// ─── ConnectInfo ──────────────────────────────────────────────────────────────
func makeDetails(publicIP, privateIP string) *upcloud.ServerDetails {
d := &upcloud.ServerDetails{}
if publicIP != "" {
d.IPAddresses = append(d.IPAddresses, upcloud.IPAddress{
Family: upcloud.IPAddressFamilyIPv4,
Access: upcloud.IPAddressAccessPublic,
Address: publicIP,
})
}
if privateIP != "" {
d.IPAddresses = append(d.IPAddresses, upcloud.IPAddress{
Family: upcloud.IPAddressFamilyIPv4,
Access: upcloud.IPAddressAccessPrivate,
Address: privateIP,
})
}
return d
}
func TestConnectInfo_Defaults(t *testing.T) {
mock := newMockSvc()
mock.getServerDetails = func(_ context.Context, _ *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error) {
return makeDetails("1.2.3.4", ""), nil
}
g := baseGroup(mock)
info, err := g.ConnectInfo(context.Background(), "uuid-1")
if err != nil {
t.Fatalf("ConnectInfo() unexpected error: %v", err)
}
if info.OS != "linux" {
t.Errorf("OS = %q, want linux", info.OS)
}
if info.Arch != "amd64" {
t.Errorf("Arch = %q, want amd64", info.Arch)
}
if info.Protocol != provider.ProtocolSSH {
t.Errorf("Protocol = %v, want SSH", info.Protocol)
}
if info.ExternalAddr != "1.2.3.4" {
t.Errorf("ExternalAddr = %q, want 1.2.3.4", info.ExternalAddr)
}
}
func TestConnectInfo_PreservesConnectorConfig(t *testing.T) {
mock := newMockSvc()
mock.getServerDetails = func(_ context.Context, _ *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error) {
return makeDetails("1.2.3.4", ""), nil
}
g := baseGroup(mock)
g.settings = provider.Settings{
ConnectorConfig: provider.ConnectorConfig{OS: "linux", Arch: "arm64", Username: "runner"},
}
info, err := g.ConnectInfo(context.Background(), "uuid-1")
if err != nil {
t.Fatalf("ConnectInfo() unexpected error: %v", err)
}
if info.Arch != "arm64" {
t.Errorf("Arch = %q, want arm64 (from ConnectorConfig)", info.Arch)
}
if info.Username != "runner" {
t.Errorf("Username = %q, want runner", info.Username)
}
}
func TestConnectInfo_UsePrivateNetwork(t *testing.T) {
mock := newMockSvc()
mock.getServerDetails = func(_ context.Context, _ *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error) {
return makeDetails("1.2.3.4", "10.0.0.5"), nil
}
g := baseGroup(mock)
g.UsePrivateNetwork = true
info, err := g.ConnectInfo(context.Background(), "uuid-1")
if err != nil {
t.Fatalf("ConnectInfo() unexpected error: %v", err)
}
if info.ExternalAddr != "10.0.0.5" {
t.Errorf("ExternalAddr = %q, want private IP 10.0.0.5", info.ExternalAddr)
}
}
func TestConnectInfo_APIError(t *testing.T) {
mock := newMockSvc()
mock.getServerDetails = func(_ context.Context, _ *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error) {
return nil, errors.New("not found")
}
g := baseGroup(mock)
if _, err := g.ConnectInfo(context.Background(), "uuid-1"); err == nil {
t.Fatal("ConnectInfo() expected error, got nil")
}
}
// ─── Heartbeat ────────────────────────────────────────────────────────────────
func TestHeartbeat_HealthyServer(t *testing.T) {
mock := newMockSvc()
mock.getServerDetails = func(_ context.Context, _ *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error) {
return &upcloud.ServerDetails{Server: upcloud.Server{State: upcloud.ServerStateStarted}}, nil
}
g := baseGroup(mock)
if err := g.Heartbeat(context.Background(), "uuid-1"); err != nil {
t.Errorf("Heartbeat() unexpected error for healthy server: %v", err)
}
}
func TestHeartbeat_ErrorState(t *testing.T) {
mock := newMockSvc()
mock.getServerDetails = func(_ context.Context, _ *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error) {
return &upcloud.ServerDetails{Server: upcloud.Server{State: upcloud.ServerStateError}}, nil
}
g := baseGroup(mock)
if err := g.Heartbeat(context.Background(), "uuid-1"); err == nil {
t.Error("Heartbeat() expected error for server in error state, got nil")
}
}
func TestHeartbeat_APIErrorTreatedAsHealthy(t *testing.T) {
mock := newMockSvc()
mock.getServerDetails = func(_ context.Context, _ *request.GetServerDetailsRequest) (*upcloud.ServerDetails, error) {
return nil, errors.New("transient network error")
}
g := baseGroup(mock)
if err := g.Heartbeat(context.Background(), "uuid-1"); err != nil {
t.Errorf("Heartbeat() should treat API errors as healthy, got: %v", err)
}
}
// ─── Init ─────────────────────────────────────────────────────────────────────
func TestInit_InvalidSSHKey(t *testing.T) {
orig := newUpcloudService
newUpcloudService = func(_ *client.Client) upcloudSvc { return newMockSvc() }
defer func() { newUpcloudService = orig }()
g := &InstanceGroup{Token: "tok", Zone: "z", Template: "t", Name: "n"}
settings := provider.Settings{
ConnectorConfig: provider.ConnectorConfig{Key: []byte("not-a-valid-pem-key")},
}
if _, err := g.Init(context.Background(), hclog.NewNullLogger(), settings); err == nil {
t.Fatal("Init() expected error for invalid SSH key, got nil")
}
}
func TestInit_GetAccountError(t *testing.T) {
mock := newMockSvc()
mock.getAccount = func(context.Context) (*upcloud.Account, error) {
return nil, errors.New("invalid credentials")
}
orig := newUpcloudService
newUpcloudService = func(_ *client.Client) upcloudSvc { return mock }
defer func() { newUpcloudService = orig }()
g := &InstanceGroup{Token: "tok", Zone: "z", Template: "t", Name: "n"}
if _, err := g.Init(context.Background(), hclog.NewNullLogger(), provider.Settings{}); err == nil {
t.Fatal("Init() expected error when GetAccount fails, got nil")
}
}
func TestInit_Success(t *testing.T) {
mock := newMockSvc()
mock.getAccount = func(context.Context) (*upcloud.Account, error) {
return &upcloud.Account{}, nil
}
orig := newUpcloudService
newUpcloudService = func(_ *client.Client) upcloudSvc { return mock }
defer func() { newUpcloudService = orig }()
g := &InstanceGroup{Token: "tok", Zone: "fi-hel1", Template: "t", Name: "n"}
info, err := g.Init(context.Background(), hclog.NewNullLogger(), provider.Settings{})
if err != nil {
t.Fatalf("Init() unexpected error: %v", err)
}
if info.MaxSize != defaultMaxSize {
t.Errorf("ProviderInfo.MaxSize = %d, want %d", info.MaxSize, defaultMaxSize)
}
if !strings.Contains(info.ID, "fi-hel1") {
t.Errorf("ProviderInfo.ID = %q, expected to contain zone", info.ID)
}
}