-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtesting_utils.go
More file actions
2209 lines (1926 loc) · 68.5 KB
/
testing_utils.go
File metadata and controls
2209 lines (1926 loc) · 68.5 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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: (C) 2025 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
package testing
import (
"context"
"fmt"
"sort"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"golang.org/x/exp/slices"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
"google.golang.org/protobuf/types/known/fieldmaskpb"
"github.com/open-edge-platform/infra-core/inventory/v2/internal/ent/hostresource"
"github.com/open-edge-platform/infra-core/inventory/v2/internal/ent/instanceresource"
"github.com/open-edge-platform/infra-core/inventory/v2/internal/ent/ipaddressresource"
netlinks "github.com/open-edge-platform/infra-core/inventory/v2/internal/ent/netlinkresource"
"github.com/open-edge-platform/infra-core/inventory/v2/internal/ent/workloadresource"
computev1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/compute/v1"
inv_v1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/inventory/v1"
localaccount_v1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/localaccount/v1"
location_v1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/location/v1"
network_v1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/network/v1"
osv1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/os/v1"
ou_v1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/ou/v1"
provider_v1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/provider/v1"
remoteaccessv1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/remoteaccess/v1"
schedule_v1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/schedule/v1"
telemetry_v1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/telemetry/v1"
tenantv1 "github.com/open-edge-platform/infra-core/inventory/v2/pkg/api/tenant/v1"
"github.com/open-edge-platform/infra-core/inventory/v2/pkg/client"
"github.com/open-edge-platform/infra-core/inventory/v2/pkg/util"
"github.com/open-edge-platform/infra-core/inventory/v2/pkg/util/collections"
)
const (
RandomSha256v1 = "49dbd0fbc4332a30651435ed20b5d3b79176b14d40b0339f245ade38f1afce2f"
RandomSha256v2 = "2d7819c0c56756caece741d1795253fb5f13cf0fd367cc860744864679a2da70"
RandomSha256v3 = "06e396c94b166ef554a456a7cff0341f4cb2b72e56dd24e2f8db5fdb9e343b9e"
DummyProviderName = "for unit testing purposes"
dummyHostName = "for unit testing purposes"
dummyInstanceName = "for unit testing purposes"
)
// ProtoEqualOrDiff Deep-compares two protobuf messages and returns a human-readable diff if they
// are not equal. This can be used to create useful error messages in unit tests:
//
// if eq, diff := ProtoEqualOrDiff(a, b); !eq {
// t.Errorf("messages are not equal: %v", diff)
// }
func ProtoEqualOrDiff(a, b proto.Message) (bool, string) {
if !proto.Equal(a, b) {
return false, cmp.Diff(a, b, protocmp.Transform())
}
return true, ""
}
// Helper function to run as pre-requisite for each helper
// using the Testing clients.
func GetClient(tb testing.TB, clientName ClientType) client.InventoryClient {
tb.Helper()
invClient := TestClients[clientName]
require.NotNil(tb, invClient)
return invClient
}
func NewInvResourceDAOOrFail(tb testing.TB) *InvResourceDAO {
tb.Helper()
return &InvResourceDAO{
apiClient: GetClient(tb, APIClient).GetTenantAwareInventoryClient(),
apiClientWatcher: TestClientsEvents[APIClient],
rmClient: GetClient(tb, RMClient).GetTenantAwareInventoryClient(),
rmClientWatcher: TestClientsEvents[RMClient],
tcClient: GetClient(tb, TCClient).GetTenantAwareInventoryClient(),
tcClientWatcher: TestClientsEvents[TCClient],
}
}
func NewInvResourceDAO() (*InvResourceDAO, error) {
apiClient := TestClients[APIClient]
if apiClient == nil {
return nil, fmt.Errorf("APIClient is not initialized yet")
}
apiClientWatcher := TestClientsEvents[APIClient]
if apiClientWatcher == nil {
return nil, fmt.Errorf("APIClientWatcher is not initialized yet")
}
rmClient := TestClients[RMClient]
if rmClient == nil {
return nil, fmt.Errorf("RMClient is not initialized yet")
}
rmClientWatcher := TestClientsEvents[RMClient]
if rmClientWatcher == nil {
return nil, fmt.Errorf("RMClientWatcher is not initialized yet")
}
tcClient := TestClients[TCClient]
if tcClient == nil {
return nil, fmt.Errorf("TCClient is not initialized yet")
}
tcClientWatcher := TestClientsEvents[TCClient]
if tcClientWatcher == nil {
return nil, fmt.Errorf("TCClientWatcher is not initialized yet")
}
return &InvResourceDAO{
apiClient: apiClient.GetTenantAwareInventoryClient(),
apiClientWatcher: apiClientWatcher,
rmClient: rmClient.GetTenantAwareInventoryClient(),
rmClientWatcher: rmClientWatcher,
tcClient: tcClient.GetTenantAwareInventoryClient(),
tcClientWatcher: tcClientWatcher,
}, nil
}
// InvResourceDAO provides set of functions allowing for simple inv resource creation/deletion.
type InvResourceDAO struct {
apiClient client.TenantAwareInventoryClient
rmClient client.TenantAwareInventoryClient
tcClient client.TenantAwareInventoryClient
apiClientWatcher chan *client.WatchEvents
rmClientWatcher chan *client.WatchEvents
tcClientWatcher chan *client.WatchEvents
}
func (c *InvResourceDAO) GetAPIClient() client.TenantAwareInventoryClient {
return c.apiClient
}
func (c *InvResourceDAO) GetRMClient() client.TenantAwareInventoryClient {
return c.rmClient
}
func (c *InvResourceDAO) GetTCClient() client.TenantAwareInventoryClient {
return c.tcClient
}
func (c *InvResourceDAO) GetAPIClientWatcher() chan *client.WatchEvents {
return c.apiClientWatcher
}
func (c *InvResourceDAO) GetRMClientWatcher() chan *client.WatchEvents {
return c.rmClientWatcher
}
func (c *InvResourceDAO) GetTCClientWatcher() chan *client.WatchEvents {
return c.tcClientWatcher
}
// The following are convenience functions to delete resources;
// they can be used at test exit with CleanUp.
func (c *InvResourceDAO) DeleteResource(tb testing.TB, tenantID, resourceID string) {
tb.Helper()
err := c.DeleteResourceAndReturnError(tb, tenantID, resourceID)
require.NoError(tb, err)
}
//nolint:revive // this is the test tool + want to keep testing.TB on first position
func (c *InvResourceDAO) DeleteAllResources(
tb testing.TB, ctx context.Context, tenantID string, kind inv_v1.ResourceKind, enforce bool,
) error {
tb.Helper()
return c.GetTCClient().DeleteAllResources(ctx, tenantID, kind, enforce)
}
func (c *InvResourceDAO) DeleteResourceAndReturnError(tb testing.TB, tenantID, resourceID string) error {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_, err := c.apiClient.Delete(ctx, tenantID, resourceID)
if err != nil {
return err
}
return nil
}
// HardDeleteTenant - hard deletes the given tenant via 2-phase deletion.
func (c *InvResourceDAO) HardDeleteTenant(tb testing.TB, tenantID, resourceID string) {
tb.Helper()
err := c.HardDeleteTenantAndReturnError(tb, tenantID, resourceID)
require.NoError(tb, err, "UpdateHost() failed")
}
// HardDeleteTenantAndReturnError - hard deletes the given host via 2-phase deletion.
func (c *InvResourceDAO) HardDeleteTenantAndReturnError(tb testing.TB, tenantID, resourceID string) error {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
c.DeleteResource(tb, tenantID, resourceID)
_, err := c.tcClient.Update(
ctx,
tenantID,
resourceID,
&fieldmaskpb.FieldMask{Paths: []string{tenantv1.TenantFieldCurrentState}},
&inv_v1.Resource{
Resource: &inv_v1.Resource_Tenant{
Tenant: &tenantv1.Tenant{
CurrentState: tenantv1.TenantState_TENANT_STATE_DELETED,
},
},
},
)
return err
}
// HardDeleteHost - hard deletes the given host via 2-phase deletion.
func (c *InvResourceDAO) HardDeleteHost(tb testing.TB, tenantID, resourceID string) {
tb.Helper()
err := c.HardDeleteHostAndReturnError(tb, tenantID, resourceID)
require.NoError(tb, err, "UpdateHost() failed")
}
// HardDeleteHostAndReturnError - hard deletes the given host via 2-phase deletion.
func (c *InvResourceDAO) HardDeleteHostAndReturnError(tb testing.TB, tenantID, resourceID string) error {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
c.DeleteResource(tb, tenantID, resourceID)
_, err := c.rmClient.Update(
ctx,
tenantID,
resourceID,
&fieldmaskpb.FieldMask{Paths: []string{hostresource.FieldCurrentState}},
&inv_v1.Resource{
Resource: &inv_v1.Resource_Host{
Host: &computev1.HostResource{
CurrentState: computev1.HostState_HOST_STATE_DELETED,
},
},
},
)
return err
}
// HardDeleteIPAddress - hard deletes is done without explicit delete. IPAddresses are removed without an explicit desired state.
func (c *InvResourceDAO) HardDeleteIPAddress(tb testing.TB, tenantID, resourceID string) {
tb.Helper()
err := c.HardDeleteIPAddressAndReturnError(tb, tenantID, resourceID)
require.NoError(tb, err, "UpdateIPAddress() failed")
}
func (c *InvResourceDAO) HardDeleteIPAddressAndReturnError(tb testing.TB, tenantID, resourceID string) error {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_, err := c.rmClient.Update(
ctx,
tenantID,
resourceID,
&fieldmaskpb.FieldMask{Paths: []string{ipaddressresource.FieldCurrentState}},
&inv_v1.Resource{
Resource: &inv_v1.Resource_Ipaddress{
Ipaddress: &network_v1.IPAddressResource{
CurrentState: network_v1.IPAddressState_IP_ADDRESS_STATE_DELETED,
},
},
},
)
return err
}
// HardDeleteInstance - hard deletes the given VM via 2-phase deletion.
func (c *InvResourceDAO) HardDeleteInstance(tb testing.TB, tenantID, resourceID string) {
tb.Helper()
err := c.HardDeleteInstanceAndReturnError(tb, tenantID, resourceID)
require.NoError(tb, err, "UpdateInstance() failed")
}
func (c *InvResourceDAO) HardDeleteInstanceAndReturnError(tb testing.TB, tenantID, resourceID string) error {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
c.DeleteResource(tb, tenantID, resourceID)
_, err := c.rmClient.Update(
ctx,
tenantID,
resourceID,
&fieldmaskpb.FieldMask{Paths: []string{instanceresource.FieldCurrentState}},
&inv_v1.Resource{
Resource: &inv_v1.Resource_Instance{
Instance: &computev1.InstanceResource{
CurrentState: computev1.InstanceState_INSTANCE_STATE_DELETED,
},
},
},
)
return err
}
// The following are convenience functions to set up entities for testing.
// They are automatically deleted at test exit.
func (c *InvResourceDAO) CreateTenantWithOpts(
tb testing.TB, tenantID string, doCleanup bool, opts ...Opt[tenantv1.Tenant],
) *tenantv1.Tenant {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
tenant := &tenantv1.Tenant{
TenantId: tenantID,
}
collections.ForEach(opts, func(opt Opt[tenantv1.Tenant]) { opt(tenant) })
rsp, err := c.GetTCClient().Create(
ctx,
tenantID,
&inv_v1.Resource{
Resource: &inv_v1.Resource_Tenant{Tenant: tenant},
},
)
require.NoError(tb, err)
tenantResp := rsp.GetTenant()
if doCleanup {
tb.Cleanup(func() { c.HardDeleteTenant(tb, tenantID, tenantResp.ResourceId) })
}
return tenantResp
}
// CreateHostWithOpts - creates Host with given options. Note this helper is not really meant to be used for the
// test of HostResource, but they are typically leveraged in case of wider
// tests involving long chain of relations that are not usually fulfilled by the eager loading.
func (c *InvResourceDAO) CreateHostWithOpts(
tb testing.TB, tenantID string, doCleanup bool, opts ...Opt[computev1.HostResource],
) (host *computev1.HostResource) {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
host = &computev1.HostResource{
Name: dummyHostName,
DesiredState: computev1.HostState_HOST_STATE_ONBOARDED,
Note: "some note",
HardwareKind: "XDgen2",
Uuid: uuid.NewString(),
MemoryBytes: 64 * util.Gigabyte, //nolint:mnd // Teting only
CpuModel: "12th Gen Intel(R) Core(TM) i9-12900",
CpuSockets: 1,
CpuCores: 14, //nolint:mnd // Teting only
CpuCapabilities: "",
CpuArchitecture: "x86_64",
CpuThreads: 10, //nolint:mnd // Teting only
MgmtIp: "192.168.10.10",
BmcKind: computev1.BaremetalControllerKind_BAREMETAL_CONTROLLER_KIND_PDU,
BmcIp: "10.0.0.10",
BmcUsername: "user",
BmcPassword: "pass",
PxeMac: "90:49:fa:ff:ff:ff",
Hostname: "testhost1",
SerialNumber: "12345678",
DesiredPowerState: computev1.PowerState_POWER_STATE_ON,
TenantId: tenantID,
}
collections.ForEach(opts, func(o Opt[computev1.HostResource]) { o(host) })
resp, err := c.apiClient.Create(ctx,
tenantID,
&inv_v1.Resource{
Resource: &inv_v1.Resource_Host{Host: host},
})
require.NoError(tb, err)
hostResp := resp.GetHost()
if doCleanup {
tb.Cleanup(func() { c.HardDeleteHost(tb, tenantID, hostResp.ResourceId) })
}
// When this test object is used in protobuf comparisons as part of another
// resource, we do not expect further embedded messages. This matches the
// structure of objects returned by ent queries, i.e. no two layers of
// embedded objects for edges.
hostResp.Site = nil
hostResp.Provider = nil
hostResp.Instance = nil
return hostResp
}
func (c *InvResourceDAO) CreateHost(
tb testing.TB, tenantID string, opts ...Opt[computev1.HostResource],
) *computev1.HostResource {
tb.Helper()
return c.CreateHostWithOpts(tb, tenantID, true, opts...)
}
func (c *InvResourceDAO) CreateHostNoCleanup(
tb testing.TB, tenantID string, opts ...Opt[computev1.HostResource],
) *computev1.HostResource {
tb.Helper()
return c.CreateHostWithOpts(tb, tenantID, false, opts...)
}
func (c *InvResourceDAO) createHostnic(
tb testing.TB,
tenantID string,
host *computev1.HostResource,
doCleanup bool,
) *computev1.HostnicResource {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
nic := &computev1.HostnicResource{
Host: host,
TenantId: tenantID,
}
resp, err := c.apiClient.Create(
ctx,
tenantID,
&inv_v1.Resource{
Resource: &inv_v1.Resource_Hostnic{Hostnic: nic},
},
)
require.NoError(tb, err)
nicResp := resp.GetHostnic()
if doCleanup {
tb.Cleanup(func() { c.DeleteResource(tb, tenantID, nicResp.ResourceId) })
}
// When this test object is used in protobuf comparisons as part of another
// resource, we do not expect further embedded messages. This matches the
// structure of objects returned by ent queries, i.e. no two layers of
// embedded objects for edges.
nicResp.Host = nil
return nicResp
}
// Create host nic. Note this helper is not really meant to be used for the
// test of HostnicResource but they are typically leveraged in case of wider
// tests involving long chain of relations that are not usually fulfilled by
// the eager loading.
func (c *InvResourceDAO) CreateHostNic(tb testing.TB, tenantID string, host *computev1.HostResource) *computev1.HostnicResource {
tb.Helper()
return c.createHostnic(tb, tenantID, host, true)
}
func (c *InvResourceDAO) CreateHostNicNoCleanup(
tb testing.TB,
tenantID string,
host *computev1.HostResource,
) (nic *computev1.HostnicResource) {
tb.Helper()
return c.createHostnic(tb, tenantID, host, false)
}
func (c *InvResourceDAO) createHostGPU(
tb testing.TB,
tenantID string,
host *computev1.HostResource,
cleanup bool,
) (gpu *computev1.HostgpuResource) {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
gpu = &computev1.HostgpuResource{
DeviceName: "Test GPU",
PciId: "00:00.1",
Product: "some product name",
Vendor: "some vendor",
Description: "for unit testing purposes",
Host: host,
TenantId: tenantID,
}
resp, err := c.apiClient.Create(
ctx,
tenantID,
&inv_v1.Resource{
Resource: &inv_v1.Resource_Hostgpu{Hostgpu: gpu},
})
require.NoError(tb, err)
gpuResp := resp.GetHostgpu()
if cleanup {
tb.Cleanup(func() { c.DeleteResource(tb, tenantID, gpuResp.ResourceId) })
}
// When this test object is used in protobuf comparisons as part of another
// resource, we do not expect further embedded messages. This matches the
// structure of objects returned by ent queries, i.e. no two layers of
// embedded objects for edges.
gpuResp.Host = nil
return gpuResp
}
func (c *InvResourceDAO) CreateHostGPU(
tb testing.TB, tenantID string, host *computev1.HostResource,
) (gpu *computev1.HostgpuResource) {
tb.Helper()
return c.createHostGPU(tb, tenantID, host, true)
}
func (c *InvResourceDAO) CreateHostGPUNoCleanup(
tb testing.TB,
tenantID string,
host *computev1.HostResource,
) (gpu *computev1.HostgpuResource) {
tb.Helper()
return c.createHostGPU(tb, tenantID, host, false)
}
// Create IPAddress. Note this helper is not really meant to be used for the
// test of IPAddressResource but they are typically leveraged in case of wider
// tests involving long chain of relations that are not usually fulfilled by
// the eager loading.
func (c *InvResourceDAO) CreateIPAddress(
tb testing.TB,
tenantID string,
hostNic *computev1.HostnicResource,
cleanup bool,
) (
ipaddress *network_v1.IPAddressResource,
) {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
ipaddress = &network_v1.IPAddressResource{
Address: "192.168.0.1/24",
CurrentState: network_v1.IPAddressState_IP_ADDRESS_STATE_CONFIGURED,
ConfigMethod: network_v1.IPAddressConfigMethod_IP_ADDRESS_CONFIG_METHOD_DYNAMIC,
Nic: hostNic,
TenantId: tenantID,
}
resp, err := c.rmClient.Create(
ctx,
tenantID,
&inv_v1.Resource{
Resource: &inv_v1.Resource_Ipaddress{Ipaddress: ipaddress},
})
if err != nil {
tb.Error(err)
tb.FailNow()
}
ipAddressResp := resp.GetIpaddress()
if cleanup {
tb.Cleanup(func() { c.HardDeleteIPAddress(tb, tenantID, ipAddressResp.ResourceId) })
}
// When this test object is used in protobuf comparisons as part of another
// resource, we do not expect further embedded messages. This matches the
// structure of objects returned by ent queries, i.e. no two layers of
// embedded objects for edges.
ipAddressResp.Nic = nil
return ipAddressResp
}
// CreateRepeatedSchedule - creates repeated schedule instance and registers cleanup hooks.
// Note this helper is not really meant to be used for the test of RepeatedScheduleResource,
// but they are typically leveraged in case of wider tests involving long chain of relations
// that are not usually fulfilled by the eager loading.
func (c *InvResourceDAO) CreateRepeatedSchedule(
tb testing.TB,
tenantID string,
opts ...Opt[schedule_v1.RepeatedScheduleResource],
) *schedule_v1.RepeatedScheduleResource {
tb.Helper()
return c.createRepeatedSchedule(tb, tenantID, true, opts...)
}
// CreateRepeatedScheduleNoCleanup - creates repeated schedule instance, do not register cleanup hooks.
// Note this helper is not really meant to be used for the test of RepeatedScheduleResource,
// but they are typically leveraged in case of wider tests involving long chain of relations
// that are not usually fulfilled by the eager loading.
func (c *InvResourceDAO) CreateRepeatedScheduleNoCleanup(
tb testing.TB,
tenantID string,
opts ...Opt[schedule_v1.RepeatedScheduleResource],
) *schedule_v1.RepeatedScheduleResource {
tb.Helper()
return c.createRepeatedSchedule(tb, tenantID, false, opts...)
}
func (c *InvResourceDAO) createRepeatedSchedule(
tb testing.TB,
tenantID string,
doCleanup bool,
opts ...Opt[schedule_v1.RepeatedScheduleResource],
) *schedule_v1.RepeatedScheduleResource {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
repeatedSchedule := &schedule_v1.RepeatedScheduleResource{
Name: "for unit testing purposes",
ScheduleStatus: schedule_v1.ScheduleStatus_SCHEDULE_STATUS_MAINTENANCE,
DurationSeconds: uint32(100), //nolint:mnd // Teting only
CronMinutes: "3",
CronHours: "4",
CronDayMonth: "5",
CronMonth: "6",
CronDayWeek: "0",
TenantId: tenantID,
}
collections.ForEach(opts, func(opt Opt[schedule_v1.RepeatedScheduleResource]) { opt(repeatedSchedule) })
resp, err := c.apiClient.Create(
ctx,
tenantID,
&inv_v1.Resource{Resource: &inv_v1.Resource_Repeatedschedule{Repeatedschedule: repeatedSchedule}},
)
require.NoError(tb, err)
repeatedScheduleResp := resp.GetRepeatedschedule()
if doCleanup {
tb.Cleanup(func() { c.DeleteResource(tb, tenantID, repeatedScheduleResp.ResourceId) })
}
// When this test object is used in protobuf comparisons as part of another
// resource, we do not expect further embedded messages. This matches the
// structure of objects returned by ent queries, i.e. no two layers of
// embedded objects for edges.
repeatedScheduleResp.Relation = nil
return repeatedScheduleResp
}
// CreateSingleSchedule - creates single schedule instance and registers cleanup hooks.
// Note this helper is not really meant to be used for the test of RepeatedScheduleResource,
// but they are typically leveraged in case of wider tests involving long chain of relations
// that are not usually fulfilled by the eager loading.
func (c *InvResourceDAO) CreateSingleSchedule(
tb testing.TB, tenantID string, opts ...Opt[schedule_v1.SingleScheduleResource],
) *schedule_v1.SingleScheduleResource {
tb.Helper()
return c.createSingleSchedule(tb, tenantID, true, opts...)
}
// CreateSingleScheduleNoCleanup - creates single schedule instance, do not register cleanup hooks.
// Note this helper is not really meant to be used for the test of RepeatedScheduleResource,
// but they are typically leveraged in case of wider tests involving long chain of relations
// that are not usually fulfilled by the eager loading.
func (c *InvResourceDAO) CreateSingleScheduleNoCleanup(
tb testing.TB, tenantID string, opts ...Opt[schedule_v1.SingleScheduleResource],
) *schedule_v1.SingleScheduleResource {
tb.Helper()
return c.createSingleSchedule(tb, tenantID, false, opts...)
}
func (c *InvResourceDAO) createSingleSchedule(
tb testing.TB,
tenantID string,
doCleanup bool,
opts ...Opt[schedule_v1.SingleScheduleResource],
) *schedule_v1.SingleScheduleResource {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
now := uint64(time.Now().Unix()) //nolint:gosec // no overflow for a few billion years
singleSchedule := &schedule_v1.SingleScheduleResource{
Name: "for unit testing purposes",
ScheduleStatus: schedule_v1.ScheduleStatus_SCHEDULE_STATUS_MAINTENANCE,
StartSeconds: now + 3600, //nolint:mnd // Testing only
EndSeconds: now + 7200, //nolint:mnd // Testing only
TenantId: tenantID,
}
collections.ForEach(opts, func(opt Opt[schedule_v1.SingleScheduleResource]) { opt(singleSchedule) })
resp, err := c.apiClient.Create(
ctx,
tenantID,
&inv_v1.Resource{Resource: &inv_v1.Resource_Singleschedule{Singleschedule: singleSchedule}},
)
require.NoError(tb, err)
singleScheduleResp := resp.GetSingleschedule()
if doCleanup {
tb.Cleanup(func() { c.DeleteResource(tb, tenantID, singleScheduleResp.ResourceId) })
}
// When this test object is used in protobuf comparisons as part of another
// resource, we do not expect further embedded messages. This matches the
// structure of objects returned by ent queries, i.e. no two layers of
// embedded objects for edges.
singleScheduleResp.Relation = nil
return singleScheduleResp
}
func (c *InvResourceDAO) CreateTelemetryGroupMetrics(
tb testing.TB, tenantID string, cleanup bool,
) *telemetry_v1.TelemetryGroupResource {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
tr := &telemetry_v1.TelemetryGroupResource{
Name: "for unit testing purposes",
Kind: telemetry_v1.TelemetryResourceKind_TELEMETRY_RESOURCE_KIND_METRICS,
CollectorKind: telemetry_v1.CollectorKind_COLLECTOR_KIND_HOST,
Groups: []string{"cpu", "memory"},
TenantId: tenantID,
}
resp, err := c.apiClient.Create(
ctx,
tenantID,
&inv_v1.Resource{Resource: &inv_v1.Resource_TelemetryGroup{TelemetryGroup: tr}},
)
require.NoError(tb, err)
trResp := resp.GetTelemetryGroup()
if cleanup {
tb.Cleanup(func() { c.DeleteResource(tb, tenantID, trResp.ResourceId) })
}
// When this test object is used in protobuf comparisons as part of another
// resource, we do not expect further embedded messages. This matches the
// structure of objects returned by ent queries, i.e. no two layers of
// embedded objects for edges.
trResp.Profiles = nil
return trResp
}
func (c *InvResourceDAO) CreateTelemetryGroupLogs(
tb testing.TB, tenantID string, cleanup bool,
) *telemetry_v1.TelemetryGroupResource {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
tr := &telemetry_v1.TelemetryGroupResource{
Name: "for unit testing purposes",
Kind: telemetry_v1.TelemetryResourceKind_TELEMETRY_RESOURCE_KIND_LOGS,
CollectorKind: telemetry_v1.CollectorKind_COLLECTOR_KIND_HOST,
Groups: []string{"kmsg"},
TenantId: tenantID,
}
resp, err := c.apiClient.Create(
ctx,
tenantID,
&inv_v1.Resource{Resource: &inv_v1.Resource_TelemetryGroup{TelemetryGroup: tr}},
)
require.NoError(tb, err)
trResp := resp.GetTelemetryGroup()
if cleanup {
tb.Cleanup(func() { c.DeleteResource(tb, tenantID, trResp.ResourceId) })
}
// When this test object is used in protobuf comparisons as part of another
// resource, we do not expect further embedded messages. This matches the
// structure of objects returned by ent queries, i.e. no two layers of
// embedded objects for edges.
trResp.Profiles = nil
return trResp
}
type TelemetryProfileTargetConfigurator Opt[telemetry_v1.TelemetryProfile]
func (c *InvResourceDAO) CreateTelemetryProfile(
tb testing.TB,
tenantID string,
configureTarget TelemetryProfileTargetConfigurator,
group *telemetry_v1.TelemetryGroupResource,
cleanup bool,
) *telemetry_v1.TelemetryProfile {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
tp := &telemetry_v1.TelemetryProfile{
Kind: group.Kind,
Group: group,
TenantId: tenantID,
}
switch group.Kind {
case telemetry_v1.TelemetryResourceKind_TELEMETRY_RESOURCE_KIND_METRICS:
tp.MetricsInterval = 300
case telemetry_v1.TelemetryResourceKind_TELEMETRY_RESOURCE_KIND_LOGS:
tp.LogLevel = telemetry_v1.SeverityLevel_SEVERITY_LEVEL_INFO
case telemetry_v1.TelemetryResourceKind_TELEMETRY_RESOURCE_KIND_UNSPECIFIED:
break
}
configureTarget(tp)
require.NotNil(tb, tp.Relation, "TelemetryProfile has to any target (Region, Site, Instance)")
resp, err := c.apiClient.Create(
ctx,
tenantID,
&inv_v1.Resource{Resource: &inv_v1.Resource_TelemetryProfile{TelemetryProfile: tp}},
)
require.NoError(tb, err)
tpResp := resp.GetTelemetryProfile()
if cleanup {
tb.Cleanup(func() { c.DeleteResource(tb, tenantID, tpResp.ResourceId) })
}
// When this test object is used in protobuf comparisons as part of another
// resource, we do not expect further embedded messages. This matches the
// structure of objects returned by ent queries, i.e. no two layers of
// embedded objects for edges.
tpResp.Group = nil
tpResp.Relation = nil
return tpResp
}
func (c *InvResourceDAO) createOsWithOpts(
tb testing.TB,
tenantID string,
doCleanup bool,
opts ...Opt[osv1.OperatingSystemResource],
) *osv1.OperatingSystemResource {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
// a default OS resource, can be overwritten by opts
osCreateReq := &osv1.OperatingSystemResource{
Name: "for unit testing purposes",
UpdateSources: []string{"test entries"},
ImageUrl: "Repo URL Test",
ImageId: "some image ID",
ProfileName: "test profile name",
ProfileVersion: "1.0.0",
Sha256: "test sha256",
InstalledPackages: "intel-opencl-icd\nintel-level-zero-gpu\nlevel-zero",
InstalledPackagesUrl: "https://manifest-url.example.com/installed-packages.txt",
SecurityFeature: osv1.SecurityFeature_SECURITY_FEATURE_SECURE_BOOT_AND_FULL_DISK_ENCRYPTION,
OsType: osv1.OsType_OS_TYPE_MUTABLE,
OsProvider: osv1.OsProviderKind_OS_PROVIDER_KIND_INFRA,
TenantId: tenantID,
}
for _, opt := range opts {
opt(osCreateReq)
}
resp, err := c.apiClient.Create(
ctx,
tenantID,
&inv_v1.Resource{Resource: &inv_v1.Resource_Os{Os: osCreateReq}},
)
require.NoError(tb, err)
osResp := resp.GetOs()
if doCleanup {
tb.Cleanup(func() { c.DeleteResource(tb, tenantID, osResp.ResourceId) })
}
return osResp
}
// Deprecated: Use CreateOsWithOpts instead.
func (c *InvResourceDAO) CreateOsWithArgs(
tb testing.TB,
tenantID, sha256Hex, name, profileName string,
feature osv1.SecurityFeature, osType osv1.OsType,
) *osv1.OperatingSystemResource {
tb.Helper()
return c.createOsWithOpts(tb, tenantID, true, func(osr *osv1.OperatingSystemResource) {
osr.Sha256 = sha256Hex
osr.ProfileName = profileName
osr.Name = name
osr.SecurityFeature = feature
osr.OsType = osType
})
}
func (c *InvResourceDAO) CreateOsWithOpts(
tb testing.TB,
tenantID string,
doCleanup bool,
opts ...Opt[osv1.OperatingSystemResource],
) *osv1.OperatingSystemResource {
tb.Helper()
return c.createOsWithOpts(tb, tenantID, doCleanup, opts...)
}
// CreateOs creates mutable OSResource by default. Use CreateOsWithOpts to customize OS fields, if needed.
func (c *InvResourceDAO) CreateOs(tb testing.TB, tenantID string) *osv1.OperatingSystemResource {
tb.Helper()
return c.createOsWithOpts(
tb,
tenantID,
true,
func(osr *osv1.OperatingSystemResource) {
osr.Sha256 = GenerateRandomSha256()
osr.ProfileName = GenerateRandomProfileName()
osr.Name = GenerateRandomOsResourceName()
osr.SecurityFeature = osv1.SecurityFeature_SECURITY_FEATURE_UNSPECIFIED
osr.OsType = osv1.OsType_OS_TYPE_MUTABLE
},
)
}
// CreateOsNoCleanup creates mutable OSResource by default (with no cleanup).
// Use CreateOsWithOpts to customize OS fields, if needed.
func (c *InvResourceDAO) CreateOsNoCleanup(tb testing.TB, tenantID string) *osv1.OperatingSystemResource {
tb.Helper()
return c.createOsWithOpts(
tb,
tenantID,
false,
func(osr *osv1.OperatingSystemResource) {
osr.Sha256 = GenerateRandomSha256()
osr.ProfileName = GenerateRandomProfileName()
osr.Name = GenerateRandomOsResourceName()
osr.SecurityFeature = osv1.SecurityFeature_SECURITY_FEATURE_UNSPECIFIED
osr.OsType = osv1.OsType_OS_TYPE_MUTABLE
},
)
}
// CreateSite - creates site and takes care about cleanup. Note this helper is not really meant to be used for the
// test of SiteResource, but they are typically leveraged in case of wider
// tests involving long chain of relations that are not usually fulfilled by the eager loading.
func (c *InvResourceDAO) CreateSite(
tb testing.TB, tenantID string, opts ...Opt[location_v1.SiteResource],
) *location_v1.SiteResource {
tb.Helper()
return c.createSite(tb, tenantID, true, opts...)
}
// CreateSiteNoCleanup - creates site and does not register cleanup handlers.
// Note this helper is not really meant to be used for the test of SiteResource, but they are typically leveraged in case of wider
// tests involving long chain of relations that are not usually fulfilled by the eager loading.
func (c *InvResourceDAO) CreateSiteNoCleanup(
tb testing.TB, tenantID string, opts ...Opt[location_v1.SiteResource],
) *location_v1.SiteResource {
tb.Helper()
return c.createSite(tb, tenantID, false, opts...)
}
func (c *InvResourceDAO) createSite(
tb testing.TB, tenantID string, doCleanup bool, opts ...Opt[location_v1.SiteResource],
) *location_v1.SiteResource {
tb.Helper()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
site := &location_v1.SiteResource{
Name: "for unit testing purposes",
DnsServers: []string{},
DockerRegistries: []string{},
TenantId: tenantID,
}
collections.ForEach(opts, func(o Opt[location_v1.SiteResource]) { o(site) })
resp, err := c.apiClient.Create(
ctx,
tenantID,
&inv_v1.Resource{
Resource: &inv_v1.Resource_Site{Site: site},
})
require.NoError(tb, err)
siteResp := resp.GetSite()
if doCleanup {
tb.Cleanup(func() { c.DeleteResource(tb, tenantID, siteResp.ResourceId) })
}
// When this test object is used in protobuf comparisons as part of another
// resource, we do not expect further embedded messages. This matches the