summaryrefslogtreecommitdiff
path: root/spec/models/clusters/cluster_spec.rb
blob: f1d4a91f289cee88b8b772828841acb7972b3e3a (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Clusters::Cluster, :use_clean_rails_memory_store_caching,
feature_category: :kubernetes_management do
  include ReactiveCachingHelpers
  include KubernetesHelpers

  it_behaves_like 'having unique enum values'

  subject(:cluster) { build(:cluster) }

  it { is_expected.to include_module(HasEnvironmentScope) }
  it { is_expected.to belong_to(:user) }
  it { is_expected.to belong_to(:management_project).class_name('::Project') }
  it { is_expected.to have_many(:cluster_projects) }
  it { is_expected.to have_many(:projects) }
  it { is_expected.to have_many(:cluster_groups) }
  it { is_expected.to have_many(:groups) }
  it { is_expected.to have_many(:groups_projects) }
  it { is_expected.to have_one(:provider_gcp) }
  it { is_expected.to have_one(:provider_aws) }
  it { is_expected.to have_one(:platform_kubernetes) }
  it { is_expected.to have_one(:integration_prometheus) }
  it { is_expected.to have_one(:application_helm) }
  it { is_expected.to have_many(:kubernetes_namespaces) }
  it { is_expected.to have_one(:cluster_project) }
  it { is_expected.to have_many(:deployment_clusters) }
  it { is_expected.to have_many(:metrics_dashboard_annotations) }
  it { is_expected.to have_many(:successful_deployments) }
  it { is_expected.to have_many(:environments).through(:deployments) }

  it { is_expected.to delegate_method(:status).to(:provider) }
  it { is_expected.to delegate_method(:status_reason).to(:provider) }

  it { is_expected.to respond_to :project }
  it { is_expected.to be_namespace_per_environment }

  describe 'default values' do
    it { expect(subject.helm_major_version).to eq(3) }
  end

  it_behaves_like 'it has loose foreign keys' do
    let(:factory_name) { :cluster }
  end

  describe 'applications have inverse_of: :cluster option' do
    let(:cluster) { create(:cluster) }
    let!(:helm) { create(:clusters_applications_helm, cluster: cluster) }

    it 'does not do a third query when referencing cluster again' do
      expect { cluster.application_helm.cluster }.not_to exceed_query_limit(2)
    end
  end

  describe '.enabled' do
    subject { described_class.enabled }

    let!(:cluster) { create(:cluster, enabled: true) }

    before do
      create(:cluster, :disabled)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.disabled' do
    subject { described_class.disabled }

    let!(:cluster) { create(:cluster, :disabled) }

    before do
      create(:cluster, enabled: true)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.user_provided' do
    subject { described_class.user_provided }

    let!(:cluster) { create(:cluster_platform_kubernetes).cluster }

    before do
      create(:cluster_provider_gcp, :created)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.gcp_provided' do
    subject { described_class.gcp_provided }

    let!(:cluster) { create(:cluster_provider_gcp, :created).cluster }

    before do
      create(:cluster, :provided_by_user)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.gcp_installed' do
    subject { described_class.gcp_installed }

    let!(:cluster) { create(:cluster_provider_gcp, :created).cluster }

    before do
      create(:cluster, :providing_by_gcp)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.aws_provided' do
    subject { described_class.aws_provided }

    let!(:cluster) { create(:cluster_provider_aws, :created).cluster }

    before do
      create(:cluster, :provided_by_user)
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.aws_installed' do
    subject { described_class.aws_installed }

    let!(:cluster) { create(:cluster_provider_aws, :created).cluster }

    before do
      errored_provider = create(:cluster_provider_aws)
      errored_provider.make_errored!("Error message")
    end

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.managed' do
    subject do
      described_class.managed
    end

    context 'cluster is not managed' do
      let!(:cluster) { create(:cluster, :not_managed) }

      it { is_expected.not_to include(cluster) }
    end

    context 'cluster is managed' do
      let!(:cluster) { create(:cluster) }

      it { is_expected.to include(cluster) }
    end
  end

  describe '.with_management_project' do
    subject { described_class.with_management_project }

    context 'cluster has a management project' do
      let!(:cluster) { create(:cluster, :management_project) }

      it { is_expected.to include(cluster) }
    end

    context 'cluster does not have a management project' do
      let!(:cluster) { create(:cluster) }

      it { is_expected.not_to include(cluster) }
    end
  end

  describe '.with_integration_prometheus' do
    subject { described_class.with_integration_prometheus }

    let!(:cluster) { create(:cluster) }

    context 'cluster has prometheus application' do
      let!(:application) { create(:clusters_integrations_prometheus, cluster: cluster) }

      it { is_expected.to include(cluster) }
    end

    context 'cluster does not have prometheus application' do
      let(:cluster) { create(:cluster) }

      it { is_expected.not_to include(cluster) }
    end
  end

  describe '.distinct_with_deployed_environments' do
    subject { described_class.distinct_with_deployed_environments }

    let_it_be(:cluster) { create(:cluster) }

    context 'cluster has multiple successful deployment with environment' do
      let!(:environment) { create(:environment) }
      let!(:deployment) { create(:deployment, :success, cluster: cluster, environment: environment) }
      let!(:deployment_2) { create(:deployment, :success, cluster: cluster, environment: environment) }

      it { is_expected.to include(cluster) }

      it 'lists only distinct environments' do
        expect(subject.first.environments.count).to eq(1)
      end
    end

    context 'cluster has only failed deployment with environment' do
      let!(:environment) { create(:environment) }
      let!(:deployment) { create(:deployment, :failed, cluster: cluster, environment: environment) }

      it { is_expected.not_to include(cluster) }
    end

    context 'cluster does not have any deployment' do
      it { is_expected.not_to include(cluster) }
    end
  end

  describe '.with_project_http_integrations' do
    subject { described_class.with_project_http_integrations(project_id) }

    let!(:cluster) { create(:cluster, :project) }
    let!(:project_id) { cluster.first_project.id }

    context 'project has alert service data' do
      let!(:integration) { create(:alert_management_http_integration, project: cluster.clusterable) }

      it { is_expected.to include(cluster) }
    end

    context 'project has no alert service data' do
      it { is_expected.not_to include(cluster) }
    end
  end

  describe '.for_project_namespace' do
    subject { described_class.for_project_namespace(namespace_id) }

    let!(:cluster) { create(:cluster, :project) }
    let!(:another_cluster) { create(:cluster, :project) }
    let(:namespace_id) { cluster.first_project.namespace_id }

    it { is_expected.to contain_exactly(cluster) }
  end

  describe '.with_name' do
    subject { described_class.with_name(name) }

    let(:name) { 'this-cluster' }
    let!(:cluster) { create(:cluster, :project, name: name) }
    let!(:another_cluster) { create(:cluster, :project) }

    it { is_expected.to contain_exactly(cluster) }
  end

  describe 'validations' do
    subject { cluster.valid? }

    context 'when validates unique_environment_scope' do
      context 'for a project cluster' do
        let(:project) { create(:project) }

        before do
          create(:cluster, projects: [project], environment_scope: 'product/*')
        end

        context 'when identical environment scope exists in project' do
          let(:cluster) { build(:cluster, projects: [project], environment_scope: 'product/*') }

          it { is_expected.to be_falsey }
        end

        context 'when identical environment scope does not exist in project' do
          let(:cluster) { build(:cluster, projects: [project], environment_scope: '*') }

          it { is_expected.to be_truthy }
        end

        context 'when identical environment scope exists in different project' do
          let(:project2) { create(:project) }
          let(:cluster) { build(:cluster, projects: [project2], environment_scope: 'product/*') }

          it { is_expected.to be_truthy }
        end
      end

      context 'for a group cluster' do
        let(:group) { create(:group) }

        before do
          create(:cluster, cluster_type: :group_type, groups: [group], environment_scope: 'product/*')
        end

        context 'when identical environment scope exists in group' do
          let(:cluster) { build(:cluster, cluster_type: :group_type, groups: [group], environment_scope: 'product/*') }

          it { is_expected.to be_falsey }
        end

        context 'when identical environment scope does not exist in group' do
          let(:cluster) { build(:cluster, cluster_type: :group_type, groups: [group], environment_scope: '*') }

          it { is_expected.to be_truthy }
        end

        context 'when identical environment scope exists in different group' do
          let(:cluster) { build(:cluster, :group, environment_scope: 'product/*') }

          it { is_expected.to be_truthy }
        end
      end

      context 'for an instance cluster' do
        before do
          create(:cluster, :instance, environment_scope: 'product/*')
        end

        context 'identical environment scope exists' do
          let(:cluster) { build(:cluster, :instance, environment_scope: 'product/*') }

          it { is_expected.to be_falsey }
        end

        context 'identical environment scope does not exist' do
          let(:cluster) { build(:cluster, :instance, environment_scope: '*') }

          it { is_expected.to be_truthy }
        end
      end
    end

    context 'when validates name' do
      context 'when provided by user' do
        let!(:cluster) { build(:cluster, :provided_by_user, name: name) }

        context 'when name is empty' do
          let(:name) { '' }

          it { is_expected.to be_falsey }
        end

        context 'when name is nil' do
          let(:name) { nil }

          it { is_expected.to be_falsey }
        end

        context 'when name is present' do
          let(:name) { 'cluster-name-1' }

          it { is_expected.to be_truthy }
        end
      end

      context 'when provided by gcp' do
        let!(:cluster) { build(:cluster, :provided_by_gcp, name: name) }

        context 'when name is shorter than 1' do
          let(:name) { '' }

          it { is_expected.to be_falsey }
        end

        context 'when name is longer than 63' do
          let(:name) { 'a' * 64 }

          it { is_expected.to be_falsey }
        end

        context 'when name includes invalid character' do
          let(:name) { '!!!!!!' }

          it { is_expected.to be_falsey }
        end

        context 'when name is present' do
          let(:name) { 'cluster-name-1' }

          it { is_expected.to be_truthy }
        end

        context 'when record is persisted' do
          let(:name) { 'cluster-name-1' }

          before do
            cluster.save!
          end

          context 'when name is changed' do
            before do
              cluster.name = 'new-cluster-name'
            end

            it { is_expected.to be_falsey }
          end

          context 'when name is same' do
            before do
              cluster.name = name
            end

            it { is_expected.to be_truthy }
          end
        end
      end
    end

    context 'when validates restrict_modification' do
      context 'when creation is on going' do
        let!(:cluster) { create(:cluster, :providing_by_gcp) }

        it { expect(cluster.update(enabled: false)).to be_falsey }
      end

      context 'when creation is done' do
        let!(:cluster) { create(:cluster, :provided_by_gcp) }

        it { expect(cluster.update(enabled: false)).to be_truthy }
      end
    end

    describe 'cluster_type validations' do
      let(:instance_cluster) { create(:cluster, :instance) }
      let(:group_cluster) { create(:cluster, :group) }
      let(:project_cluster) { create(:cluster, :project) }

      it 'validates presence' do
        cluster = build(:cluster, :project, cluster_type: nil)

        expect(cluster).not_to be_valid
        expect(cluster.errors.full_messages).to include("Cluster type can't be blank")
      end

      context 'project_type cluster' do
        it 'does not allow setting group' do
          project_cluster.groups << build(:group)

          expect(project_cluster).not_to be_valid
          expect(project_cluster.errors.full_messages).to include('Cluster cannot have groups assigned')
        end
      end

      context 'group_type cluster' do
        it 'does not allow setting project' do
          group_cluster.projects << build(:project)

          expect(group_cluster).not_to be_valid
          expect(group_cluster.errors.full_messages).to include('Cluster cannot have projects assigned')
        end
      end

      context 'instance_type cluster' do
        it 'does not allow setting group' do
          instance_cluster.groups << build(:group)

          expect(instance_cluster).not_to be_valid
          expect(instance_cluster.errors.full_messages).to include('Cluster cannot have groups assigned')
        end

        it 'does not allow setting project' do
          instance_cluster.projects << build(:project)

          expect(instance_cluster).not_to be_valid
          expect(instance_cluster.errors.full_messages).to include('Cluster cannot have projects assigned')
        end
      end
    end

    describe 'domain validation' do
      let(:cluster) { build(:cluster) }

      subject { cluster }

      context 'when cluster has domain' do
        let(:cluster) { build(:cluster, :with_domain) }

        it { is_expected.to be_valid }
      end

      context 'when cluster is not a valid hostname' do
        let(:cluster) { build(:cluster, domain: 'http://not.a.valid.hostname') }

        it 'adds an error on domain' do
          expect(subject).not_to be_valid
          expect(subject.errors[:domain].first).to eq('contains invalid characters (valid characters: [a-z0-9\\-])')
        end
      end

      context 'when cluster does not have a domain' do
        it { is_expected.to be_valid }
      end
    end

    describe 'unique scope for management_project' do
      let(:project) { create(:project) }
      let!(:cluster_with_management_project) { create(:cluster, management_project: project) }

      context 'duplicate scopes for the same management project' do
        let(:cluster) { build(:cluster, management_project: project) }

        it 'adds an error on environment_scope' do
          expect(cluster).not_to be_valid
          expect(cluster.errors[:environment_scope].first).to eq('cannot add duplicated environment scope')
        end
      end
    end

    describe 'helm_major_version can only be 2 or 3' do
      using RSpec::Parameterized::TableSyntax

      where(:helm_major_version, :expect_valid) do
        2  | true
        3  | true
        4  | false
        -1 | false
      end

      with_them do
        let(:cluster) { build(:cluster, helm_major_version: helm_major_version) }

        it { is_expected.to eq(expect_valid) }
      end
    end
  end

  it 'has default helm_major_version 3' do
    expect(create(:cluster).helm_major_version).to eq(3)
  end

  describe '.ancestor_clusters_for_clusterable' do
    let(:group_cluster) { create(:cluster, :provided_by_gcp, :group) }
    let(:group) { group_cluster.group }
    let(:hierarchy_order) { :desc }
    let(:clusterable) { project }

    subject do
      described_class.ancestor_clusters_for_clusterable(clusterable, hierarchy_order: hierarchy_order)
    end

    context 'when project does not belong to this group' do
      let(:project) { create(:project, group: create(:group)) }

      it 'returns nothing' do
        is_expected.to be_empty
      end
    end

    context 'when group has a configured kubernetes cluster' do
      let(:project) { create(:project, group: group) }

      it 'returns the group cluster' do
        is_expected.to eq([group_cluster])
      end
    end

    context 'when group and instance have configured kubernetes clusters' do
      let(:project) { create(:project, group: group) }
      let!(:instance_cluster) { create(:cluster, :provided_by_gcp, :instance) }

      it 'returns clusters in order, descending the hierachy' do
        is_expected.to eq([group_cluster, instance_cluster])
      end
    end

    context 'when sub-group has configured kubernetes cluster' do
      let(:sub_group_cluster) { create(:cluster, :provided_by_gcp, :group) }
      let(:sub_group) { sub_group_cluster.group }
      let(:project) { create(:project, group: sub_group) }

      before do
        sub_group.update!(parent: group)
      end

      it 'returns clusters in order, descending the hierachy' do
        is_expected.to eq([group_cluster, sub_group_cluster])
      end

      it 'avoids N+1 queries' do
        another_project = create(:project)
        control_count = ActiveRecord::QueryRecorder.new do
          described_class.ancestor_clusters_for_clusterable(another_project, hierarchy_order: hierarchy_order)
        end.count

        cluster2 = create(:cluster, :provided_by_gcp, :group)
        child2 = cluster2.group
        child2.update!(parent: sub_group)
        project = create(:project, group: child2)

        expect do
          described_class.ancestor_clusters_for_clusterable(project, hierarchy_order: hierarchy_order)
        end.not_to exceed_query_limit(control_count)
      end

      context 'for a group' do
        let(:clusterable) { sub_group }

        it 'returns clusters in order for a group' do
          is_expected.to eq([group_cluster])
        end
      end
    end

    context 'scope chaining' do
      let(:project) { create(:project, group: group) }

      subject { described_class.none.ancestor_clusters_for_clusterable(project) }

      it 'returns nothing' do
        is_expected.to be_empty
      end
    end
  end

  describe '#provider' do
    subject { cluster.provider }

    context 'when provider is gcp' do
      let(:cluster) { create(:cluster, :provided_by_gcp) }

      it 'returns a provider' do
        is_expected.to eq(cluster.provider_gcp)
      end
    end

    context 'when provider is aws' do
      let(:cluster) { create(:cluster, :provided_by_aws) }

      it 'returns a provider' do
        is_expected.to eq(cluster.provider_aws)
      end
    end

    context 'when provider is user' do
      let(:cluster) { create(:cluster, :provided_by_user) }

      it { is_expected.to be_nil }
    end
  end

  describe '#platform' do
    subject { cluster.platform }

    context 'when platform is kubernetes' do
      let(:cluster) { create(:cluster, :provided_by_user) }

      it 'returns a platform' do
        is_expected.to eq(cluster.platform_kubernetes)
        expect(subject.class.name.deconstantize).to eq(Clusters::Platforms.to_s)
      end
    end
  end

  describe '#first_project' do
    subject { cluster.first_project }

    context 'when cluster belongs to a project' do
      let(:cluster) { create(:cluster, :project) }
      let(:project) { Clusters::Project.find_by_cluster_id(cluster.id).project }

      it { is_expected.to eq(project) }
    end

    context 'when cluster does not belong to projects' do
      let(:cluster) { create(:cluster) }

      it { is_expected.to be_nil }
    end
  end

  describe '#group' do
    subject { cluster.group }

    context 'when cluster belongs to a group' do
      let(:cluster) { create(:cluster, :group) }
      let(:group) { cluster.groups.first }

      it { is_expected.to eq(group) }
    end

    context 'when cluster does not belong to any group' do
      let(:cluster) { create(:cluster) }

      it { is_expected.to be_nil }
    end
  end

  describe '.with_persisted_applications' do
    let(:cluster) { create(:cluster) }
    let!(:helm) { create(:clusters_applications_helm, :installed, cluster: cluster) }

    it 'preloads persisted applications' do
      query_rec = ActiveRecord::QueryRecorder.new do
        described_class.with_persisted_applications.find_by_id(cluster.id).application_helm
      end

      expect(query_rec.count).to eq(1)
    end
  end

  describe '#persisted_applications' do
    let(:cluster) { create(:cluster) }

    subject { cluster.persisted_applications }

    context 'when applications are created' do
      let!(:helm) { create(:clusters_applications_helm, cluster: cluster) }

      it 'returns a list of created applications' do
        is_expected.to contain_exactly(helm)
      end
    end
  end

  describe '#applications' do
    let_it_be(:cluster, reload: true) { create(:cluster) }

    subject { cluster.applications }

    context 'when none of applications are created' do
      it 'returns a list of a new objects' do
        is_expected.not_to be_empty
      end
    end

    context 'when applications are created' do
      let(:cluster) { create(:cluster, :with_all_applications) }

      it 'returns a list of created applications', :aggregate_failures do
        is_expected.to have_attributes(size: described_class::APPLICATIONS.size)
        is_expected.to all(be_kind_of(::Clusters::Concerns::ApplicationCore))
        is_expected.to all(be_persisted)
      end
    end
  end

  describe '#find_or_build_application' do
    let_it_be(:cluster, reload: true) { create(:cluster) }

    it 'rejects classes that are not applications' do
      expect do
        cluster.find_or_build_application(Project)
      end.to raise_error(ArgumentError)
    end

    context 'when none of applications are created' do
      it 'returns the new application', :aggregate_failures do
        described_class::APPLICATIONS.values.each do |application_class|
          application = cluster.find_or_build_application(application_class)

          expect(application).to be_a(application_class)
          expect(application).not_to be_persisted
        end
      end
    end

    context 'when application is persisted' do
      let(:cluster) { create(:cluster, :with_all_applications) }

      it 'returns the persisted application', :aggregate_failures do
        described_class::APPLICATIONS.each_value do |application_class|
          application = cluster.find_or_build_application(application_class)

          expect(application).to be_kind_of(::Clusters::Concerns::ApplicationCore)
          expect(application).to be_persisted
        end
      end
    end
  end

  describe '#allow_user_defined_namespace?' do
    subject { cluster.allow_user_defined_namespace? }

    context 'project type cluster' do
      context 'gitlab managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp) }

        it { is_expected.to be_truthy }
      end

      context 'not managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp, managed: false) }

        it { is_expected.to be_truthy }
      end
    end

    context 'group type cluster' do
      context 'gitlab managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp, :group) }

        it { is_expected.to be_falsey }
      end

      context 'not managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp, :group, managed: false) }

        it { is_expected.to be_truthy }
      end
    end

    context 'instance type cluster' do
      context 'gitlab managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp, :instance) }

        it { is_expected.to be_falsey }
      end

      context 'not managed' do
        let(:cluster) { build(:cluster, :provided_by_gcp, :instance, managed: false) }

        it { is_expected.to be_truthy }
      end
    end
  end

  describe '#all_projects' do
    context 'cluster_type is project_type' do
      let(:project) { create(:project) }
      let(:cluster) { create(:cluster, :with_installed_helm, projects: [project]) }

      it 'returns projects' do
        expect(cluster.all_projects).to match_array [project]
      end
    end

    context 'cluster_type is group_type' do
      let(:group) { create(:group) }
      let!(:project) { create(:project, group: group) }
      let(:cluster) { create(:cluster_for_group, :with_installed_helm, groups: [group]) }

      it 'returns group projects' do
        expect(cluster.all_projects.ids).to match_array [project.id]
      end
    end

    context 'cluster_type is instance_type' do
      let!(:project) { create(:project) }
      let(:cluster) { create(:cluster, :instance) }

      it "returns all instance's projects" do
        expect(cluster.all_projects.ids).to match_array [project.id]
      end
    end
  end

  describe '#kube_ingress_domain' do
    let(:cluster) { build(:cluster, :provided_by_gcp) }

    subject { cluster.kube_ingress_domain }

    context 'with domain set in cluster' do
      let(:cluster) { build(:cluster, :provided_by_gcp, :with_domain) }

      it { is_expected.to eq(cluster.domain) }
    end

    context 'with no domain on cluster' do
      let(:cluster) { build(:cluster, :project, :provided_by_gcp) }
      let(:project) { cluster.project }

      context 'with domain set at instance level' do
        before do
          stub_application_setting(auto_devops_domain: 'global_domain.com')
        end

        it { is_expected.to eq('global_domain.com') }
      end
    end
  end

  describe '#kubernetes_namespace_for' do
    subject { cluster.kubernetes_namespace_for(environment, deployable: build) }

    let(:environment_name) { 'the-environment-name' }
    let(:environment) { create(:environment, name: environment_name, project: cluster.project) }
    let(:build) { create(:ci_build, environment: environment, project: cluster.project) }
    let(:cluster) { create(:cluster, :project, managed: managed_cluster) }
    let(:managed_cluster) { true }
    let(:default_namespace) { Gitlab::Kubernetes::DefaultNamespace.new(cluster, project: cluster.project).from_environment_slug(environment.slug) }
    let(:build_options) { {} }

    it 'validates the project id' do
      environment.project_id = build.project_id + 1
      expect { subject }.to raise_error ArgumentError, 'environment.project_id must match deployable.project_id'
    end

    context 'when environment has no last_deployable' do
      let(:build) { nil }

      it { is_expected.to eq default_namespace }
    end

    context 'when cluster is managed' do
      before do
        build.options = { environment: { kubernetes: { namespace: 'ci yaml namespace' } } }
      end

      it 'returns the cached namespace if present, ignoring CI config' do
        cached_namespace = create(:cluster_kubernetes_namespace, cluster: cluster, environment: environment, namespace: 'the name', service_account_token: 'some token')
        expect(subject).to eq cached_namespace.namespace
      end

      it 'returns the default namespace when no cached namespace, ignoring CI config' do
        expect(subject).to eq default_namespace
      end
    end

    context 'when cluster is not managed' do
      let(:managed_cluster) { false }

      it 'returns the cached namespace if present, regardless of CI config' do
        cached_namespace = create(:cluster_kubernetes_namespace, cluster: cluster, environment: environment, namespace: 'the name', service_account_token: 'some token')
        build.options = { environment: { kubernetes: { namespace: 'ci yaml namespace' } } }
        expect(subject).to eq cached_namespace.namespace
      end

      it 'returns the CI YAML namespace when configured' do
        build.options = { environment: { kubernetes: { namespace: 'ci yaml namespace' } } }
        expect(subject).to eq 'ci yaml namespace'
      end

      it 'returns the default namespace when no namespace is configured' do
        expect(subject).to eq default_namespace
      end
    end
  end

  describe '#predefined_variables' do
    subject { cluster.predefined_variables }

    context 'with an instance domain' do
      let(:cluster) { create(:cluster, :provided_by_gcp) }

      before do
        stub_application_setting(auto_devops_domain: 'global_domain.com')
      end

      it 'includes KUBE_INGRESS_BASE_DOMAIN' do
        expect(subject.to_hash).to include(KUBE_INGRESS_BASE_DOMAIN: 'global_domain.com')
      end
    end

    context 'with a cluster domain' do
      let(:cluster) { create(:cluster, :provided_by_gcp, domain: 'example.com') }

      it 'includes KUBE_INGRESS_BASE_DOMAIN' do
        expect(subject.to_hash).to include(KUBE_INGRESS_BASE_DOMAIN: 'example.com')
      end
    end

    context 'with no domain' do
      let(:cluster) { build(:cluster, :provided_by_gcp, :project) }

      it 'returns an empty array' do
        expect(subject.to_hash).to be_empty
      end
    end
  end

  describe '#provided_by_user?' do
    subject { cluster.provided_by_user? }

    context 'with a GCP provider' do
      let(:cluster) { create(:cluster, :provided_by_gcp) }

      it { is_expected.to be_falsy }
    end

    context 'with an user provider' do
      let(:cluster) { create(:cluster, :provided_by_user) }

      it { is_expected.to be_truthy }
    end
  end

  describe '#status_name' do
    subject { cluster.status_name }

    context 'the cluster has a provider' do
      let(:cluster) { build(:cluster, :provided_by_gcp) }
      let(:provider_status) { :errored }

      before do
        cluster.provider.make_errored!
      end

      it { is_expected.to eq provider_status }

      context 'when cluster cleanup is ongoing' do
        using RSpec::Parameterized::TableSyntax

        where(:status_name, :cleanup_status) do
          provider_status  | :cleanup_not_started
          :cleanup_ongoing | :cleanup_removing_project_namespaces
          :cleanup_ongoing | :cleanup_removing_service_account
          :cleanup_errored | :cleanup_errored
        end

        with_them do
          it 'returns cleanup_ongoing when uninstalling applications' do
            cluster.cleanup_status = described_class
              .state_machines[:cleanup_status]
              .states[cleanup_status]
              .value

            is_expected.to eq status_name
          end
        end
      end
    end

    context 'there is a cached connection status' do
      let(:cluster) { build(:cluster, :provided_by_user) }

      before do
        allow(cluster).to receive(:connection_status).and_return(:connected)
      end

      it { is_expected.to eq :connected }
    end

    context 'there is no connection status in the cache' do
      let(:cluster) { build(:cluster, :provided_by_user) }

      before do
        allow(cluster).to receive(:connection_status).and_return(nil)
      end

      it { is_expected.to eq :created }
    end
  end

  describe 'cleanup_status state_machine' do
    shared_examples 'cleanup_status transition' do
      let(:cluster) { create(:cluster, from_state) }

      it 'transitions cleanup_status correctly' do
        expect { subject }.to change { cluster.cleanup_status_name }
          .from(from_state).to(to_state)
      end

      it 'schedules a Clusters::Cleanup::*Worker' do
        expect(expected_worker_class).to receive(:perform_async).with(cluster.id)
        subject
      end
    end

    describe '#start_cleanup!' do
      let(:expected_worker_class) { Clusters::Cleanup::ProjectNamespaceWorker }
      let(:to_state) { :cleanup_removing_project_namespaces }

      subject { cluster.start_cleanup! }

      context 'when cleanup_status is cleanup_not_started' do
        let(:from_state) { :cleanup_not_started }

        it_behaves_like 'cleanup_status transition'
      end

      context 'when cleanup_status is errored' do
        let(:from_state) { :cleanup_errored }

        it_behaves_like 'cleanup_status transition'
      end
    end

    describe '#make_cleanup_errored!' do
      non_errored_states = Clusters::Cluster.state_machines[:cleanup_status].states.keys - [:cleanup_errored]

      non_errored_states.each do |state|
        it "transitions cleanup_status from #{state} to cleanup_errored" do
          cluster = create(:cluster, state)

          expect { cluster.make_cleanup_errored! }.to change { cluster.cleanup_status_name }
            .from(state).to(:cleanup_errored)
        end

        it "sets error message" do
          cluster = create(:cluster, state)

          expect { cluster.make_cleanup_errored!("Error Message") }.to change { cluster.cleanup_status_reason }
            .from(nil).to("Error Message")
        end
      end
    end

    describe '#continue_cleanup!' do
      let(:expected_worker_class) { Clusters::Cleanup::ServiceAccountWorker }
      let(:from_state) { :cleanup_removing_project_namespaces }
      let(:to_state) { :cleanup_removing_service_account }

      subject { cluster.continue_cleanup! }

      it_behaves_like 'cleanup_status transition'
    end
  end

  describe '#connection_status' do
    let(:cluster) { create(:cluster) }
    let(:status) { :connected }

    subject { cluster.connection_status }

    it { is_expected.to be_nil }

    context 'with a cached status' do
      before do
        stub_reactive_cache(cluster, connection_status: status)
      end

      it { is_expected.to eq(status) }
    end
  end

  describe '#connection_error' do
    let(:cluster) { create(:cluster) }
    let(:error) { :unknown_error }

    subject { cluster.connection_error }

    it { is_expected.to be_nil }

    context 'with a cached status' do
      before do
        stub_reactive_cache(cluster, connection_error: error)
      end

      it { is_expected.to eq(error) }
    end
  end

  describe '#node_connection_error' do
    let(:cluster) { create(:cluster) }
    let(:error) { :unknown_error }

    subject { cluster.node_connection_error }

    it { is_expected.to be_nil }

    context 'with a cached status' do
      before do
        stub_reactive_cache(cluster, node_connection_error: error)
      end

      it { is_expected.to eq(error) }
    end
  end

  describe '#metrics_connection_error' do
    let(:cluster) { create(:cluster) }
    let(:error) { :unknown_error }

    subject { cluster.metrics_connection_error }

    it { is_expected.to be_nil }

    context 'with a cached status' do
      before do
        stub_reactive_cache(cluster, metrics_connection_error: error)
      end

      it { is_expected.to eq(error) }
    end
  end

  describe '#nodes' do
    let(:cluster) { create(:cluster) }

    subject { cluster.nodes }

    it { is_expected.to be_nil }

    context 'with a cached status' do
      before do
        stub_reactive_cache(cluster, nodes: [kube_node])
      end

      it { is_expected.to eq([kube_node]) }
    end
  end

  describe '#calculate_reactive_cache' do
    subject { cluster.calculate_reactive_cache }

    context 'cluster is disabled' do
      let(:cluster) { create(:cluster, :disabled) }

      it 'does not populate the cache' do
        expect(cluster).not_to receive(:retrieve_connection_status)
        expect(cluster).not_to receive(:retrieve_nodes)

        is_expected.to be_nil
      end
    end

    context 'cluster is enabled' do
      let(:cluster) { create(:cluster, :provided_by_user, :group) }
      let(:gl_k8s_node_double) { double(Gitlab::Kubernetes::Node) }
      let(:expected_nodes) { {} }

      before do
        stub_kubeclient_discover(cluster.platform.api_url)
        allow(Gitlab::Kubernetes::Node).to receive(:new).with(cluster).and_return(gl_k8s_node_double)
        allow(gl_k8s_node_double).to receive(:all).and_return(expected_nodes)
      end

      context 'connection to the cluster is successful' do
        let(:expected_nodes) { { nodes: [kube_node.merge(kube_node_metrics)] } }
        let(:connection_status) { { connection_status: :connected } }

        before do
          allow(gl_k8s_node_double).to receive(:all).and_return(expected_nodes)
        end

        it { is_expected.to eq(**connection_status, **expected_nodes) }
      end

      context 'cluster cannot be reached' do
        let(:connection_status) { { connection_status: :unreachable, connection_error: :connection_error } }

        before do
          allow(cluster.kubeclient.core_client).to receive(:discover)
            .and_raise(SocketError)
        end

        it { is_expected.to eq(**connection_status, **expected_nodes) }
      end

      context 'cluster cannot be authenticated to' do
        let(:connection_status) { { connection_status: :authentication_failure, connection_error: :authentication_error } }

        before do
          allow(cluster.kubeclient.core_client).to receive(:discover)
            .and_raise(OpenSSL::X509::CertificateError.new("Certificate error"))
        end

        it { is_expected.to eq(**connection_status, **expected_nodes) }
      end

      describe 'Kubeclient::HttpError' do
        let(:connection_status) { { connection_status: :authentication_failure, connection_error: :http_error } }
        let(:error_code) { 403 }
        let(:error_message) { "Forbidden" }

        before do
          allow(cluster.kubeclient.core_client).to receive(:discover)
            .and_raise(Kubeclient::HttpError.new(error_code, error_message, nil))
        end

        it { is_expected.to eq(**connection_status, **expected_nodes) }

        context 'generic timeout' do
          let(:connection_status) { { connection_status: :unreachable, connection_error: :http_error } }
          let(:error_message) { 'Timed out connecting to server' }

          it { is_expected.to eq(**connection_status, **expected_nodes) }
        end

        context 'gateway timeout' do
          let(:connection_status) { { connection_status: :unreachable, connection_error: :http_error } }
          let(:error_message) { '504 Gateway Timeout for GET https://kubernetes.example.com/api/v1' }

          it { is_expected.to eq(**connection_status, **expected_nodes) }
        end
      end

      context 'an uncategorised error is raised' do
        let(:connection_status) { { connection_status: :unknown_failure, connection_error: :unknown_error } }

        before do
          allow(cluster.kubeclient.core_client).to receive(:discover)
            .and_raise(StandardError)
        end

        it { is_expected.to eq(**connection_status, **expected_nodes) }

        it 'notifies Sentry' do
          expect(Gitlab::ErrorTracking).to receive(:track_exception)
            .with(instance_of(StandardError), hash_including(cluster_id: cluster.id))
            .once

          subject
        end
      end
    end
  end

  describe '#integration_prometheus_available?' do
    let_it_be_with_reload(:cluster) { create(:cluster, :project) }

    subject { cluster.integration_prometheus_available? }

    it { is_expected.to be_falsey }

    context 'when integration is enabled' do
      let!(:integration) { create(:clusters_integrations_prometheus, cluster: cluster) }

      it { is_expected.to be_truthy }
    end

    context 'when integration is disabled' do
      let!(:integration) { create(:clusters_integrations_prometheus, enabled: false, cluster: cluster) }

      it { is_expected.to be_falsey }
    end
  end

  describe '#prometheus_adapter' do
    let_it_be_with_reload(:cluster) { create(:cluster, :project) }

    it 'returns nothing' do
      expect(cluster.prometheus_adapter).to be_nil
    end

    context 'has integration_prometheus' do
      let_it_be(:integration) { create(:clusters_integrations_prometheus, cluster: cluster) }

      it 'returns the integration' do
        expect(cluster.prometheus_adapter).to eq(integration)
      end
    end
  end

  describe '#delete_cached_resources!' do
    let!(:cluster) { create(:cluster, :project) }
    let!(:staging_namespace) { create(:cluster_kubernetes_namespace, cluster: cluster, namespace: 'staging') }
    let!(:production_namespace) { create(:cluster_kubernetes_namespace, cluster: cluster, namespace: 'production') }

    subject { cluster.delete_cached_resources! }

    it 'deletes associated namespace records' do
      expect(cluster.kubernetes_namespaces).to match_array([staging_namespace, production_namespace])

      subject

      expect(cluster.kubernetes_namespaces).to be_empty
    end
  end

  describe '#clusterable' do
    subject { cluster.clusterable }

    context 'project type' do
      let(:cluster) { create(:cluster, :project) }

      it { is_expected.to eq(cluster.project) }
    end

    context 'group type' do
      let(:cluster) { create(:cluster, :group) }

      it { is_expected.to eq(cluster.group) }
    end

    context 'instance type' do
      let(:cluster) { create(:cluster, :instance) }

      it { is_expected.to be_a(Clusters::Instance) }
    end

    context 'unknown type' do
      let(:cluster) { create(:cluster, :project) }

      before do
        allow(cluster).to receive(:cluster_type).and_return('unknown_type')
      end

      it 'raises NotImplementedError' do
        expect { subject }.to raise_error(NotImplementedError)
      end
    end
  end

  describe '#on_creation?' do
    subject(:on_creation?) { cluster.on_creation? }

    before do
      allow(cluster).to receive(:provider).and_return(provider)
    end

    context 'without provider' do
      let(:provider) {}

      it { is_expected.to eq(false) }
    end

    context 'with provider' do
      let(:provider) { instance_double(Clusters::Providers::Gcp, on_creation?: on_creation?) }

      before do
        allow(cluster).to receive(:provider).and_return(provider)
      end

      context 'with on_creation? set to true' do
        let(:on_creation?) { true }

        it { is_expected.to eq(true) }
      end

      context 'with on_creation? set to false' do
        let(:on_creation?) { false }

        it { is_expected.to eq(false) }
      end
    end
  end

  describe '#platform_kubernetes_active?' do
    subject(:platform_kubernetes_active?) { cluster.platform_kubernetes_active? }

    before do
      allow(cluster).to receive(:platform_kubernetes).and_return(platform_kubernetes)
    end

    context 'without platform_kubernetes' do
      let(:platform_kubernetes) {}

      it { is_expected.to eq(false) }
    end

    context 'with platform_kubernetes' do
      let(:platform_kubernetes) { instance_double(Clusters::Platforms::Kubernetes, active?: active?) }

      context 'with active? set to true' do
        let(:active?) { true }

        it { is_expected.to eq(true) }
      end

      context 'with active? set to false' do
        let(:active?) { false }

        it { is_expected.to eq(false) }
      end
    end
  end

  describe '#platform_kubernetes_rbac?' do
    subject(:platform_kubernetes_rbac?) { cluster.platform_kubernetes_rbac? }

    before do
      allow(cluster).to receive(:platform_kubernetes).and_return(platform_kubernetes)
    end

    context 'without platform_kubernetes' do
      let(:platform_kubernetes) {}

      it { is_expected.to eq(false) }
    end

    context 'with platform_kubernetes' do
      let(:platform_kubernetes) { instance_double(Clusters::Platforms::Kubernetes, rbac?: rbac?) }

      context 'with rbac? set to true' do
        let(:rbac?) { true }

        it { is_expected.to eq(true) }
      end

      context 'with rbac? set to false' do
        let(:rbac?) { false }

        it { is_expected.to eq(false) }
      end
    end
  end

  describe '#application_helm_available?' do
    subject(:application_helm_available?) { cluster.application_helm_available? }

    before do
      allow(cluster).to receive(:application_helm).and_return(application_helm)
    end

    context 'without application_helm' do
      let(:application_helm) {}

      it { is_expected.to eq(false) }
    end

    context 'with application_helm' do
      let(:application_helm) { instance_double(Clusters::Applications::Helm, available?: available?) }

      context 'with available? set to true' do
        let(:available?) { true }

        it { is_expected.to eq(true) }
      end

      context 'with available? set to false' do
        let(:available?) { false }

        it { is_expected.to eq(false) }
      end
    end
  end
end