summaryrefslogtreecommitdiff
path: root/spec/requests/api/groups_spec.rb
blob: 1c359b6e50fda91773abc1711880ef77631bfd51 (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
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe API::Groups do
  include GroupAPIHelpers
  include UploadHelpers

  let_it_be(:user1) { create(:user, can_create_group: false) }
  let_it_be(:user2) { create(:user) }
  let_it_be(:user3) { create(:user) }
  let_it_be(:admin) { create(:admin) }
  let_it_be(:group1) { create(:group, avatar: File.open(uploaded_image_temp_path)) }
  let_it_be(:group2) { create(:group, :private) }
  let_it_be(:project1) { create(:project, namespace: group1) }
  let_it_be(:project2) { create(:project, namespace: group2) }
  let_it_be(:project3) { create(:project, namespace: group1, path: 'test', visibility_level: Gitlab::VisibilityLevel::PRIVATE) }
  let_it_be(:archived_project) { create(:project, namespace: group1, archived: true) }

  before do
    group1.add_owner(user1)
    group2.add_owner(user2)
  end

  shared_examples 'group avatar upload' do
    context 'when valid' do
      let(:file_path) { 'spec/fixtures/banana_sample.gif' }

      it 'returns avatar url in response' do
        make_upload_request

        group_id = json_response['id']
        expect(json_response['avatar_url']).to eq('http://localhost/uploads/'\
                                                  '-/system/group/avatar/'\
                                                  "#{group_id}/banana_sample.gif")
      end
    end

    context 'when invalid' do
      shared_examples 'invalid file upload request' do
        it 'returns 400' do
          make_upload_request

          expect(response).to have_gitlab_http_status(:bad_request)
          expect(response.message).to eq('Bad Request')
          expect(json_response['message'].to_s).to match(/#{message}/)
        end
      end

      context 'when file format is not supported' do
        let(:file_path) { 'spec/fixtures/doc_sample.txt' }
        let(:message)   { 'file format is not supported. Please try one of the following supported formats: image/png, image/jpeg, image/gif, image/bmp, image/tiff, image/vnd.microsoft.icon' }

        it_behaves_like 'invalid file upload request'
      end

      context 'when file is too large' do
        let(:file_path) { 'spec/fixtures/big-image.png' }
        let(:message)   { 'is too big' }

        it_behaves_like 'invalid file upload request'
      end
    end
  end

  describe "GET /groups" do
    context "when unauthenticated" do
      it "returns public groups" do
        get api("/groups")

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(1)
        expect(json_response.first['created_at']).to be_present
        expect(json_response)
          .to satisfy_one { |group| group['name'] == group1.name }
      end

      it 'avoids N+1 queries' do
        # Establish baseline
        get api("/groups", admin)

        control = ActiveRecord::QueryRecorder.new do
          get api("/groups", admin)
        end

        create(:group)

        expect do
          get api("/groups", admin)
        end.not_to exceed_query_limit(control)
      end

      context 'when statistics are requested' do
        it 'does not include statistics' do
          get api("/groups"), params: { statistics: true }

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to include_pagination_headers
          expect(json_response).to be_an Array
          expect(json_response.first).not_to include 'statistics'
        end
      end
    end

    context "when authenticated as user" do
      it "normal user: returns an array of groups of user1" do
        get api("/groups", user1)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(1)
        expect(json_response)
          .to satisfy_one { |group| group['name'] == group1.name }
      end

      it "does not include runners_token information" do
        get api("/groups", user1)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(1)
        expect(json_response.first).not_to include('runners_token')
      end

      it "does not include statistics" do
        get api("/groups", user1), params: { statistics: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.first).not_to include 'statistics'
      end

      it "includes a created_at timestamp" do
        get api("/groups", user1)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.first['created_at']).to be_present
      end
    end

    context "when authenticated as admin" do
      it "admin: returns an array of all groups" do
        get api("/groups", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(2)
      end

      it "does not include runners_token information" do
        get api("/groups", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(2)
        expect(json_response.first).not_to include('runners_token')
      end

      it "does not include statistics by default" do
        get api("/groups", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.first).not_to include('statistics')
      end

      it "includes a created_at timestamp" do
        get api("/groups", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.first['created_at']).to be_present
      end

      it "includes statistics if requested" do
        attributes = {
          storage_size: 2392,
          repository_size: 123,
          wiki_size: 456,
          lfs_objects_size: 234,
          build_artifacts_size: 345,
          snippets_size: 1234
        }.stringify_keys
        exposed_attributes = attributes.dup
        exposed_attributes['job_artifacts_size'] = exposed_attributes.delete('build_artifacts_size')

        project1.statistics.update!(attributes)

        get api("/groups", admin), params: { statistics: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response)
          .to satisfy_one { |group| group['statistics'] == exposed_attributes }
      end
    end

    context "when using skip_groups in request" do
      it "returns all groups excluding skipped groups" do
        get api("/groups", admin), params: { skip_groups: [group2.id] }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(1)
      end
    end

    context "when using all_available in request" do
      let(:response_groups) { json_response.map { |group| group['name'] } }

      it "returns all groups you have access to" do
        public_group = create :group, :public

        get api("/groups", user1), params: { all_available: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(response_groups).to contain_exactly(public_group.name, group1.name)
      end
    end

    context "when using top_level_only" do
      let(:top_level_group) { create(:group, name: 'top-level-group') }
      let(:subgroup) { create(:group, :nested, name: 'subgroup') }
      let(:response_groups) { json_response.map { |group| group['name'] } }

      before do
        top_level_group.add_owner(user1)
        subgroup.add_owner(user1)
      end

      it "doesn't return subgroups" do
        get api("/groups", user1), params: { top_level_only: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(response_groups).to include(top_level_group.name)
        expect(response_groups).not_to include(subgroup.name)
      end
    end

    context "when using sorting" do
      let(:group3) { create(:group, name: "a#{group1.name}", path: "z#{group1.path}") }
      let(:group4) { create(:group, name: "same-name", path: "y#{group1.path}") }
      let(:group5) { create(:group, name: "same-name") }
      let(:response_groups) { json_response.map { |group| group['name'] } }
      let(:response_groups_ids) { json_response.map { |group| group['id'] } }

      before do
        group3.add_owner(user1)
        group4.add_owner(user1)
        group5.add_owner(user1)
      end

      it "sorts by name ascending by default" do
        get api("/groups", user1)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(response_groups).to eq(groups_visible_to_user(user1).order(:name).pluck(:name))
      end

      it "sorts in descending order when passed" do
        get api("/groups", user1), params: { sort: "desc" }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(response_groups).to eq(groups_visible_to_user(user1).order(name: :desc).pluck(:name))
      end

      it "sorts by path in order_by param" do
        get api("/groups", user1), params: { order_by: "path" }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(response_groups).to eq(groups_visible_to_user(user1).order(:path).pluck(:name))
      end

      it "sorts by id in the order_by param" do
        get api("/groups", user1), params: { order_by: "id" }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(response_groups).to eq(groups_visible_to_user(user1).order(:id).pluck(:name))
      end

      it "sorts also by descending id with pagination fix" do
        get api("/groups", user1), params: { order_by: "id", sort: "desc" }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(response_groups).to eq(groups_visible_to_user(user1).order(id: :desc).pluck(:name))
      end

      it "sorts identical keys by id for good pagination" do
        get api("/groups", user1), params: { search: "same-name", order_by: "name" }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(response_groups_ids).to eq(Group.select { |group| group['name'] == 'same-name' }.map { |group| group['id'] }.sort)
      end

      it "sorts descending identical keys by id for good pagination" do
        get api("/groups", user1), params: { search: "same-name", order_by: "name", sort: "desc" }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(response_groups_ids).to eq(Group.select { |group| group['name'] == 'same-name' }.map { |group| group['id'] }.sort)
      end

      def groups_visible_to_user(user)
        Group.where(id: user.authorized_groups.select(:id).reorder(nil))
      end
    end

    context 'when using owned in the request' do
      it 'returns an array of groups the user owns' do
        group1.add_maintainer(user2)

        get api('/groups', user2), params: { owned: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(1)
        expect(json_response.first['name']).to eq(group2.name)
      end
    end

    context 'when using min_access_level in the request' do
      let!(:group3) { create(:group, :private) }
      let(:response_groups) { json_response.map { |group| group['id'] } }

      before do
        group1.add_developer(user2)
        group3.add_maintainer(user2)
      end

      it 'returns an array of groups the user has at least master access' do
        get api('/groups', user2), params: { min_access_level: 40 }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(response_groups).to contain_exactly(group2.id, group3.id)
      end
    end
  end

  describe "GET /groups/:id" do
    # Given a group, create one project for each visibility level
    #
    # group      - Group to add projects to
    # share_with - If provided, each project will be shared with this Group
    #
    # Returns a Hash of visibility_level => Project pairs
    def add_projects_to_group(group, share_with: nil)
      projects = {
        public:   create(:project, :public,   namespace: group),
        internal: create(:project, :internal, namespace: group),
        private:  create(:project, :private,  namespace: group)
      }

      if share_with
        create(:project_group_link, project: projects[:public],   group: share_with)
        create(:project_group_link, project: projects[:internal], group: share_with)
        create(:project_group_link, project: projects[:private],  group: share_with)
      end

      projects
    end

    def response_project_ids(json_response, key)
      json_response[key].map do |project|
        project['id'].to_i
      end
    end

    context 'when unauthenticated' do
      it 'returns 404 for a private group' do
        get api("/groups/#{group2.id}")

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it 'returns 200 for a public group' do
        get api("/groups/#{group1.id}")

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).not_to include('runners_token')
        expect(json_response).to include('created_at')
      end

      it 'returns only public projects in the group' do
        public_group = create(:group, :public)
        projects = add_projects_to_group(public_group)

        get api("/groups/#{public_group.id}")

        expect(response_project_ids(json_response, 'projects'))
          .to contain_exactly(projects[:public].id)
      end

      it 'returns only public projects shared with the group' do
        public_group = create(:group, :public)
        projects = add_projects_to_group(public_group, share_with: group1)

        get api("/groups/#{group1.id}")

        expect(response_project_ids(json_response, 'shared_projects'))
          .to contain_exactly(projects[:public].id)
      end
    end

    context "when authenticated as user" do
      it "returns one of user1's groups" do
        project = create(:project, namespace: group2, path: 'Foo')
        create(:project_group_link, project: project, group: group1)
        group = create(:group)
        link = create(:group_group_link, shared_group: group1, shared_with_group: group)

        get api("/groups/#{group1.id}", user1)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response['id']).to eq(group1.id)
        expect(json_response['name']).to eq(group1.name)
        expect(json_response['path']).to eq(group1.path)
        expect(json_response['description']).to eq(group1.description)
        expect(json_response['visibility']).to eq(Gitlab::VisibilityLevel.string_level(group1.visibility_level))
        expect(json_response['avatar_url']).to eq(group1.avatar_url(only_path: false))
        expect(json_response['share_with_group_lock']).to eq(group1.share_with_group_lock)
        expect(json_response['require_two_factor_authentication']).to eq(group1.require_two_factor_authentication)
        expect(json_response['two_factor_grace_period']).to eq(group1.two_factor_grace_period)
        expect(json_response['auto_devops_enabled']).to eq(group1.auto_devops_enabled)
        expect(json_response['emails_disabled']).to eq(group1.emails_disabled)
        expect(json_response['mentions_disabled']).to eq(group1.mentions_disabled)
        expect(json_response['project_creation_level']).to eq('maintainer')
        expect(json_response['subgroup_creation_level']).to eq('maintainer')
        expect(json_response['web_url']).to eq(group1.web_url)
        expect(json_response['request_access_enabled']).to eq(group1.request_access_enabled)
        expect(json_response['full_name']).to eq(group1.full_name)
        expect(json_response['full_path']).to eq(group1.full_path)
        expect(json_response['parent_id']).to eq(group1.parent_id)
        expect(json_response['created_at']).to be_present
        expect(json_response['shared_with_groups']).to be_an Array
        expect(json_response['shared_with_groups'].length).to eq(1)
        expect(json_response['shared_with_groups'][0]['group_id']).to eq(group.id)
        expect(json_response['shared_with_groups'][0]['group_name']).to eq(group.name)
        expect(json_response['shared_with_groups'][0]['group_full_path']).to eq(group.full_path)
        expect(json_response['shared_with_groups'][0]['group_access_level']).to eq(link.group_access)
        expect(json_response['shared_with_groups'][0]).to have_key('expires_at')
        expect(json_response['projects']).to be_an Array
        expect(json_response['projects'].length).to eq(3)
        expect(json_response['shared_projects']).to be_an Array
        expect(json_response['shared_projects'].length).to eq(1)
        expect(json_response['shared_projects'][0]['id']).to eq(project.id)
      end

      it "returns one of user1's groups without projects when with_projects option is set to false" do
        project = create(:project, namespace: group2, path: 'Foo')
        create(:project_group_link, project: project, group: group1)

        get api("/groups/#{group1.id}", user1), params: { with_projects: false }

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response['projects']).to be_nil
        expect(json_response['shared_projects']).to be_nil
        expect(json_response).not_to include('runners_token')
      end

      it "doesn't return runners_token if the user is not the owner of the group" do
        get api("/groups/#{group1.id}", user3)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).not_to include('runners_token')
      end

      it "returns runners_token if the user is the owner of the group" do
        group1.add_owner(user3)
        get api("/groups/#{group1.id}", user3)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).to include('runners_token')
      end

      it "does not return a non existing group" do
        get api("/groups/1328", user1)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it "does not return a group not attached to user1" do
        get api("/groups/#{group2.id}", user1)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it 'returns only public and internal projects in the group' do
        public_group = create(:group, :public)
        projects = add_projects_to_group(public_group)

        get api("/groups/#{public_group.id}", user2)

        expect(response_project_ids(json_response, 'projects'))
          .to contain_exactly(projects[:public].id, projects[:internal].id)
      end

      it 'returns only public and internal projects shared with the group' do
        public_group = create(:group, :public)
        projects = add_projects_to_group(public_group, share_with: group1)

        get api("/groups/#{group1.id}", user2)

        expect(response_project_ids(json_response, 'shared_projects'))
          .to contain_exactly(projects[:public].id, projects[:internal].id)
      end

      it 'avoids N+1 queries with project links' do
        get api("/groups/#{group1.id}", admin)

        control_count = ActiveRecord::QueryRecorder.new do
          get api("/groups/#{group1.id}", admin)
        end.count

        create(:project, namespace: group1)

        expect do
          get api("/groups/#{group1.id}", admin)
        end.not_to exceed_query_limit(control_count)
      end

      it 'avoids N+1 queries with shared group links' do
        # setup at least 1 shared group, so that we record the queries that preload the nested associations too.
        create(:group_group_link, shared_group: group1, shared_with_group: create(:group))

        control_count = ActiveRecord::QueryRecorder.new do
          get api("/groups/#{group1.id}", admin)
        end.count

        # setup "n" more shared groups
        create(:group_group_link, shared_group: group1, shared_with_group: create(:group))
        create(:group_group_link, shared_group: group1, shared_with_group: create(:group))

        # test that no of queries for 1 shared group is same as for n shared groups
        expect do
          get api("/groups/#{group1.id}", admin)
        end.not_to exceed_query_limit(control_count)
      end
    end

    context "when authenticated as admin" do
      it "returns any existing group" do
        get api("/groups/#{group2.id}", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response['name']).to eq(group2.name)
      end

      it "returns information of the runners_token for the group" do
        get api("/groups/#{group2.id}", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).to include('runners_token')
      end

      it "does not return a non existing group" do
        get api("/groups/1328", admin)

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end

    context 'when using group path in URL' do
      it 'returns any existing group' do
        get api("/groups/#{group1.path}", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response['name']).to eq(group1.name)
      end

      it 'does not return a non existing group' do
        get api('/groups/unknown', admin)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it 'does not return a group not attached to user1' do
        get api("/groups/#{group2.path}", user1)

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end

    context 'limiting the number of projects and shared_projects in the response' do
      let(:limit) { 1 }

      before do
        stub_const("GroupProjectsFinder::DEFAULT_PROJECTS_LIMIT", limit)

        # creates 3 public projects
        create_list(:project, 3, :public, namespace: group1)

        # creates 3 shared projects
        public_group = create(:group, :public)
        projects_to_be_shared = create_list(:project, 3, :public, namespace: public_group)

        projects_to_be_shared.each do |project|
          create(:project_group_link, project: project, group: group1)
        end
      end

      context 'when limiting feature is enabled' do
        before do
          stub_feature_flags(limit_projects_in_groups_api: true)
        end

        it 'limits projects and shared_projects' do
          get api("/groups/#{group1.id}")

          expect(json_response['projects'].count).to eq(limit)
          expect(json_response['shared_projects'].count).to eq(limit)
        end
      end

      context 'when limiting feature is not enabled' do
        before do
          stub_feature_flags(limit_projects_in_groups_api: false)
        end

        it 'does not limit projects and shared_projects' do
          get api("/groups/#{group1.id}")

          expect(json_response['projects'].count).to eq(3)
          expect(json_response['shared_projects'].count).to eq(3)
        end
      end
    end
  end

  describe 'PUT /groups/:id' do
    let(:new_group_name) { 'New Group'}
    let(:file_path) { 'spec/fixtures/dk.png' }

    it_behaves_like 'group avatar upload' do
      def make_upload_request
        group_param = {
          avatar: fixture_file_upload(file_path)
        }
        put api("/groups/#{group1.id}", user1), params: group_param
      end
    end

    context 'when authenticated as the group owner' do
      it 'updates the group' do
        put api("/groups/#{group1.id}", user1), params: {
          name: new_group_name,
          request_access_enabled: true,
          project_creation_level: "noone",
          subgroup_creation_level: "maintainer",
          default_branch_protection: ::Gitlab::Access::MAINTAINER_PROJECT_ACCESS,
          avatar: fixture_file_upload(file_path)
        }

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response['name']).to eq(new_group_name)
        expect(json_response['description']).to eq('')
        expect(json_response['visibility']).to eq('public')
        expect(json_response['share_with_group_lock']).to eq(false)
        expect(json_response['require_two_factor_authentication']).to eq(false)
        expect(json_response['two_factor_grace_period']).to eq(48)
        expect(json_response['auto_devops_enabled']).to eq(nil)
        expect(json_response['emails_disabled']).to eq(nil)
        expect(json_response['mentions_disabled']).to eq(nil)
        expect(json_response['project_creation_level']).to eq("noone")
        expect(json_response['subgroup_creation_level']).to eq("maintainer")
        expect(json_response['request_access_enabled']).to eq(true)
        expect(json_response['parent_id']).to eq(nil)
        expect(json_response['created_at']).to be_present
        expect(json_response['projects']).to be_an Array
        expect(json_response['projects'].length).to eq(3)
        expect(json_response['shared_projects']).to be_an Array
        expect(json_response['shared_projects'].length).to eq(0)
        expect(json_response['default_branch_protection']).to eq(::Gitlab::Access::MAINTAINER_PROJECT_ACCESS)
        expect(json_response['avatar_url']).to end_with('dk.png')
      end

      context 'updating the `default_branch_protection` attribute' do
        subject do
          put api("/groups/#{group1.id}", user1), params: { default_branch_protection: ::Gitlab::Access::PROTECTION_NONE }
        end

        context 'for users who have the ability to update default_branch_protection' do
          it 'updates the attribute' do
            subject

            expect(response).to have_gitlab_http_status(:ok)
            expect(json_response['default_branch_protection']).to eq(Gitlab::Access::PROTECTION_NONE)
          end
        end

        context 'for users who does not have the ability to update default_branch_protection`' do
          it 'does not update the attribute' do
            allow(Ability).to receive(:allowed?).and_call_original
            allow(Ability).to receive(:allowed?).with(user1, :update_default_branch_protection, group1) { false }

            subject

            expect(response).to have_gitlab_http_status(:ok)
            expect(json_response['default_branch_protection']).not_to eq(Gitlab::Access::PROTECTION_NONE)
          end
        end
      end

      context 'malicious group name' do
        subject { put api("/groups/#{group1.id}", user1), params: { name: "<SCRIPT>alert('DOUBLE-ATTACK!')</SCRIPT>" } }

        it 'returns bad request' do
          subject

          expect(response).to have_gitlab_http_status(:bad_request)
        end

        it 'does not update group name' do
          expect { subject }.not_to change { group1.reload.name }
        end
      end

      it 'returns 404 for a non existing group' do
        put api('/groups/1328', user1), params: { name: new_group_name }

        expect(response).to have_gitlab_http_status(:not_found)
      end

      context 'within a subgroup' do
        let(:group3) { create(:group, visibility_level: Gitlab::VisibilityLevel::PUBLIC) }
        let!(:subgroup) { create(:group, parent: group3, visibility_level: Gitlab::VisibilityLevel::PUBLIC) }

        before do
          group3.add_owner(user3)
        end

        it 'does not change visibility when not requested' do
          put api("/groups/#{group3.id}", user3), params: { description: 'Bug #23083' }

          expect(response).to have_gitlab_http_status(:ok)
          expect(json_response['visibility']).to eq('public')
        end

        it 'prevents making private a group containing public subgroups' do
          put api("/groups/#{group3.id}", user3), params: { visibility: 'private' }

          expect(response).to have_gitlab_http_status(:bad_request)
          expect(json_response['message']['visibility_level']).to contain_exactly('private is not allowed since there are sub-groups with higher visibility.')
        end
      end
    end

    context 'when authenticated as the admin' do
      it 'updates the group' do
        put api("/groups/#{group1.id}", admin), params: { name: new_group_name }

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response['name']).to eq(new_group_name)
      end
    end

    context 'when authenticated as an user that can see the group' do
      it 'does not updates the group' do
        put api("/groups/#{group1.id}", user2), params: { name: new_group_name }

        expect(response).to have_gitlab_http_status(:forbidden)
      end
    end

    context 'when authenticated as an user that cannot see the group' do
      it 'returns 404 when trying to update the group' do
        put api("/groups/#{group2.id}", user1), params: { name: new_group_name }

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end
  end

  describe "GET /groups/:id/projects" do
    context "when authenticated as user" do
      context 'with min access level' do
        it 'returns projects with min access level or higher' do
          group_guest = create(:user)
          group1.add_guest(group_guest)
          project4 = create(:project, group: group1)
          project1.add_guest(group_guest)
          project3.add_reporter(group_guest)
          project4.add_developer(group_guest)

          get api("/groups/#{group1.id}/projects", group_guest), params: { min_access_level: Gitlab::Access::REPORTER }

          project_ids = json_response.map { |proj| proj['id'] }
          expect(project_ids).to match_array([project3.id, project4.id])
        end
      end

      it "returns the group's projects" do
        get api("/groups/#{group1.id}/projects", user1)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response.length).to eq(3)
        project_names = json_response.map { |proj| proj['name'] }
        expect(project_names).to match_array([project1.name, project3.name, archived_project.name])
        expect(json_response.first['visibility']).to be_present
      end

      context 'and using archived' do
        it "returns the group's archived projects" do
          get api("/groups/#{group1.id}/projects?archived=true", user1)

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to include_pagination_headers
          expect(json_response).to be_an Array
          expect(json_response.length).to eq(Project.public_or_visible_to_user(user1).where(archived: true).size)
          expect(json_response.map { |project| project['id'] }).to include(archived_project.id)
        end

        it "returns the group's non-archived projects" do
          get api("/groups/#{group1.id}/projects?archived=false", user1)

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to include_pagination_headers
          expect(json_response).to be_an Array
          expect(json_response.length).to eq(Project.public_or_visible_to_user(user1).where(archived: false).size)
          expect(json_response.map { |project| project['id'] }).not_to include(archived_project.id)
        end

        it "returns all of the group's projects" do
          get api("/groups/#{group1.id}/projects", user1)

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to include_pagination_headers
          expect(json_response).to be_an Array
          expect(json_response.map { |project| project['id'] }).to contain_exactly(*Project.public_or_visible_to_user(user1).pluck(:id))
        end
      end

      context 'with similarity ordering' do
        let_it_be(:group_with_projects) { create(:group) }
        let_it_be(:project_1) { create(:project, name: 'Project', path: 'project', group: group_with_projects) }
        let_it_be(:project_2) { create(:project, name: 'Test Project', path: 'test-project', group: group_with_projects) }
        let_it_be(:project_3) { create(:project, name: 'Test', path: 'test', group: group_with_projects) }

        let(:params) { { order_by: 'similarity', search: 'test' } }

        subject { get api("/groups/#{group_with_projects.id}/projects", user1), params: params }

        before do
          group_with_projects.add_owner(user1)
        end

        it 'returns items based ordered by similarity' do
          subject

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to include_pagination_headers
          expect(json_response.length).to eq(2)

          project_names = json_response.map { |proj| proj['name'] }
          expect(project_names).to eq(['Test', 'Test Project'])
        end

        context 'when `search` parameter is not given' do
          before do
            params.delete(:search)
          end

          it 'returns items ordered by name' do
            subject

            expect(response).to have_gitlab_http_status(:ok)
            expect(response).to include_pagination_headers
            expect(json_response.length).to eq(3)

            project_names = json_response.map { |proj| proj['name'] }
            expect(project_names).to eq(['Project', 'Test', 'Test Project'])
          end
        end

        context 'when `similarity_search` feature flag is off' do
          before do
            stub_feature_flags(similarity_search: false)
          end

          it 'returns items ordered by name' do
            subject

            expect(response).to have_gitlab_http_status(:ok)
            expect(response).to include_pagination_headers
            expect(json_response.length).to eq(2)

            project_names = json_response.map { |proj| proj['name'] }
            expect(project_names).to eq(['Test', 'Test Project'])
          end
        end
      end

      it "returns the group's projects with simple representation" do
        get api("/groups/#{group1.id}/projects", user1), params: { simple: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response.length).to eq(3)
        project_names = json_response.map { |proj| proj['name'] }
        expect(project_names).to match_array([project1.name, project3.name, archived_project.name])
        expect(json_response.first['visibility']).not_to be_present
      end

      it "filters the groups projects" do
        public_project = create(:project, :public, path: 'test1', group: group1)

        get api("/groups/#{group1.id}/projects", user1), params: { visibility: 'public' }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an(Array)
        expect(json_response.length).to eq(1)
        expect(json_response.first['name']).to eq(public_project.name)
      end

      it "returns projects excluding shared" do
        create(:project_group_link, project: create(:project), group: group1)
        create(:project_group_link, project: create(:project), group: group1)
        create(:project_group_link, project: create(:project), group: group1)

        get api("/groups/#{group1.id}/projects", user1), params: { with_shared: false }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an(Array)
        expect(json_response.length).to eq(3)
      end

      it "returns projects including those in subgroups" do
        subgroup = create(:group, parent: group1)
        create(:project, group: subgroup)
        create(:project, group: subgroup)

        get api("/groups/#{group1.id}/projects", user1), params: { include_subgroups: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an(Array)
        expect(json_response.length).to eq(5)
      end

      it "does not return a non existing group" do
        get api("/groups/1328/projects", user1)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it "does not return a group not attached to user1" do
        get api("/groups/#{group2.id}/projects", user1)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it "only returns projects to which user has access" do
        project3.add_developer(user3)

        get api("/groups/#{group1.id}/projects", user3)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response.length).to eq(1)
        expect(json_response.first['name']).to eq(project3.name)
      end

      it 'only returns the projects owned by user' do
        project2.group.add_owner(user3)

        get api("/groups/#{project2.group.id}/projects", user3), params: { owned: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response.length).to eq(1)
        expect(json_response.first['name']).to eq(project2.name)
      end

      it 'only returns the projects starred by user' do
        user1.starred_projects = [project1]

        get api("/groups/#{group1.id}/projects", user1), params: { starred: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response.length).to eq(1)
        expect(json_response.first['name']).to eq(project1.name)
      end
    end

    context "when authenticated as admin" do
      it "returns any existing group" do
        get api("/groups/#{group2.id}/projects", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response.length).to eq(1)
        expect(json_response.first['name']).to eq(project2.name)
      end

      it "does not return a non existing group" do
        get api("/groups/1328/projects", admin)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it 'avoids N+1 queries' do
        get api("/groups/#{group1.id}/projects", admin)

        control_count = ActiveRecord::QueryRecorder.new do
          get api("/groups/#{group1.id}/projects", admin)
        end.count

        create(:project, namespace: group1)

        expect do
          get api("/groups/#{group1.id}/projects", admin)
        end.not_to exceed_query_limit(control_count)
      end
    end

    context 'when using group path in URL' do
      it 'returns any existing group' do
        get api("/groups/#{group1.path}/projects", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        project_names = json_response.map { |proj| proj['name'] }
        expect(project_names).to match_array([project1.name, project3.name, archived_project.name])
      end

      it 'does not return a non existing group' do
        get api('/groups/unknown/projects', admin)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it 'does not return a group not attached to user1' do
        get api("/groups/#{group2.path}/projects", user1)

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end
  end

  describe "GET /groups/:id/projects/shared" do
    let!(:project4) do
      create(:project, namespace: group2, path: 'test_project', visibility_level: Gitlab::VisibilityLevel::PRIVATE)
    end

    let(:path) { "/groups/#{group1.id}/projects/shared" }

    before do
      create(:project_group_link, project: project2, group: group1)
      create(:project_group_link, project: project4, group: group1)
    end

    context 'when authenticated as user' do
      it 'returns the shared projects in the group' do
        get api(path, user1)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response.length).to eq(2)
        project_ids = json_response.map { |project| project['id'] }
        expect(project_ids).to match_array([project2.id, project4.id])
        expect(json_response.first['visibility']).to be_present
      end

      it 'returns shared projects with min access level or higher' do
        user = create(:user)

        project2.add_guest(user)
        project4.add_reporter(user)

        get api(path, user), params: { min_access_level: Gitlab::Access::REPORTER }

        expect(json_response).to be_an(Array)
        expect(json_response.length).to eq(1)
        expect(json_response.first['id']).to eq(project4.id)
      end

      it 'returns the shared projects of the group with simple representation' do
        get api(path, user1), params: { simple: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response.length).to eq(2)
        project_ids = json_response.map { |project| project['id'] }
        expect(project_ids).to match_array([project2.id, project4.id])
        expect(json_response.first['visibility']).not_to be_present
      end

      it 'filters the shared projects in the group based on visibility' do
        internal_project = create(:project, :internal, namespace: create(:group))

        create(:project_group_link, project: internal_project, group: group1)

        get api(path, user1), params: { visibility: 'internal' }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an(Array)
        expect(json_response.length).to eq(1)
        expect(json_response.first['id']).to eq(internal_project.id)
      end

      it 'filters the shared projects in the group based on search params' do
        get api(path, user1), params: { search: 'test_project' }

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an(Array)
        expect(json_response.length).to eq(1)
        expect(json_response.first['id']).to eq(project4.id)
      end

      it 'does not return the projects owned by the group' do
        get api(path, user1)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an(Array)
        project_ids = json_response.map { |project| project['id'] }

        expect(project_ids).not_to include(project1.id)
      end

      it 'returns 404 for a non-existing group' do
        get api("/groups/0000/projects/shared", user1)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it 'does not return a group not attached to the user' do
        group = create(:group, :private)

        get api("/groups/#{group.id}/projects/shared", user1)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it 'only returns shared projects to which user has access' do
        project4.add_developer(user3)

        get api(path, user3)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response.length).to eq(1)
        expect(json_response.first['id']).to eq(project4.id)
      end

      it 'only returns the projects starred by user' do
        user1.starred_projects = [project2]

        get api(path, user1), params: { starred: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response.length).to eq(1)
        expect(json_response.first['id']).to eq(project2.id)
      end
    end

    context "when authenticated as admin" do
      subject { get api(path, admin) }

      it "returns shared projects of an existing group" do
        subject

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response.length).to eq(2)
        project_ids = json_response.map { |project| project['id'] }
        expect(project_ids).to match_array([project2.id, project4.id])
      end

      context 'for a non-existent group' do
        let(:path) { "/groups/000/projects/shared" }

        it 'returns 404 for a non-existent group' do
          subject

          expect(response).to have_gitlab_http_status(:not_found)
        end
      end

      it 'avoids N+1 queries' do
        control_count = ActiveRecord::QueryRecorder.new do
          subject
        end.count

        create(:project_group_link, project: create(:project), group: group1)

        expect do
          subject
        end.not_to exceed_query_limit(control_count)
      end
    end

    context 'when using group path in URL' do
      let(:path) { "/groups/#{group1.path}/projects/shared" }

      it 'returns the right details' do
        get api(path, admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response.length).to eq(2)
        project_ids = json_response.map { |project| project['id'] }
        expect(project_ids).to match_array([project2.id, project4.id])
      end

      it 'returns 404 for a non-existent group' do
        get api('/groups/unknown/projects/shared', admin)

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end
  end

  describe 'GET /groups/:id/subgroups' do
    let!(:subgroup1) { create(:group, parent: group1) }
    let!(:subgroup2) { create(:group, :private, parent: group1) }
    let!(:subgroup3) { create(:group, :private, parent: group2) }

    context 'when unauthenticated' do
      it 'returns only public subgroups' do
        get api("/groups/#{group1.id}/subgroups")

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(1)
        expect(json_response.first['id']).to eq(subgroup1.id)
        expect(json_response.first['parent_id']).to eq(group1.id)
      end

      it 'returns 404 for a private group' do
        get api("/groups/#{group2.id}/subgroups")

        expect(response).to have_gitlab_http_status(:not_found)
      end

      context 'when statistics are requested' do
        it 'does not include statistics' do
          get api("/groups/#{group1.id}/subgroups"), params: { statistics: true }

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to include_pagination_headers
          expect(json_response).to be_an Array
          expect(json_response.first).not_to include 'statistics'
        end
      end
    end

    context 'when authenticated as user' do
      context 'when user is not member of a public group' do
        it 'returns no subgroups for the public group' do
          get api("/groups/#{group1.id}/subgroups", user2)

          expect(response).to have_gitlab_http_status(:ok)
          expect(json_response).to be_an Array
          expect(json_response.length).to eq(0)
        end

        context 'when using all_available in request' do
          it 'returns public subgroups' do
            get api("/groups/#{group1.id}/subgroups", user2), params: { all_available: true }

            expect(response).to have_gitlab_http_status(:ok)
            expect(json_response).to be_an Array
            expect(json_response.length).to eq(1)
            expect(json_response[0]['id']).to eq(subgroup1.id)
            expect(json_response[0]['parent_id']).to eq(group1.id)
          end
        end
      end

      context 'when user is not member of a private group' do
        it 'returns 404 for the private group' do
          get api("/groups/#{group2.id}/subgroups", user1)

          expect(response).to have_gitlab_http_status(:not_found)
        end
      end

      context 'when user is member of public group' do
        before do
          group1.add_guest(user2)
        end

        it 'returns private subgroups' do
          get api("/groups/#{group1.id}/subgroups", user2)

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to include_pagination_headers
          expect(json_response).to be_an Array
          expect(json_response.length).to eq(2)
          private_subgroups = json_response.select { |group| group['visibility'] == 'private' }
          expect(private_subgroups.length).to eq(1)
          expect(private_subgroups.first['id']).to eq(subgroup2.id)
          expect(private_subgroups.first['parent_id']).to eq(group1.id)
        end

        context 'when using statistics in request' do
          it 'does not include statistics' do
            get api("/groups/#{group1.id}/subgroups", user2), params: { statistics: true }

            expect(response).to have_gitlab_http_status(:ok)
            expect(json_response).to be_an Array
            expect(json_response.first).not_to include 'statistics'
          end
        end
      end

      context 'when user is member of private group' do
        before do
          group2.add_guest(user1)
        end

        it 'returns subgroups' do
          get api("/groups/#{group2.id}/subgroups", user1)

          expect(response).to have_gitlab_http_status(:ok)
          expect(json_response).to be_an Array
          expect(json_response.length).to eq(1)
          expect(json_response.first['id']).to eq(subgroup3.id)
          expect(json_response.first['parent_id']).to eq(group2.id)
        end
      end
    end

    context 'when authenticated as admin' do
      it 'returns private subgroups of a public group' do
        get api("/groups/#{group1.id}/subgroups", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(2)
      end

      it 'returns subgroups of a private group' do
        get api("/groups/#{group2.id}/subgroups", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(1)
      end

      it 'does not include statistics by default' do
        get api("/groups/#{group1.id}/subgroups", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).to be_an Array
        expect(json_response.first).not_to include('statistics')
      end

      it 'includes statistics if requested' do
        get api("/groups/#{group1.id}/subgroups", admin), params: { statistics: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).to be_an Array
        expect(json_response.first).to include('statistics')
      end
    end
  end

  describe 'GET /groups/:id/descendant_groups' do
    let_it_be(:child_group1) { create(:group, parent: group1) }
    let_it_be(:private_child_group1) { create(:group, :private, parent: group1) }
    let_it_be(:sub_child_group1) { create(:group, parent: child_group1) }
    let_it_be(:child_group2) { create(:group, :private, parent: group2) }
    let_it_be(:sub_child_group2) { create(:group, :private, parent: child_group2) }
    let(:response_groups) { json_response.map { |group| group['name'] } }

    context 'when unauthenticated' do
      it 'returns only public descendants' do
        get api("/groups/#{group1.id}/descendant_groups")

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to include_pagination_headers
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(2)
        expect(response_groups).to contain_exactly(child_group1.name, sub_child_group1.name)
      end

      it 'returns 404 for a private group' do
        get api("/groups/#{group2.id}/descendant_groups")

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end

    context 'when authenticated as user' do
      context 'when user is not member of a public group' do
        it 'returns no descendants for the public group' do
          get api("/groups/#{group1.id}/descendant_groups", user2)

          expect(response).to have_gitlab_http_status(:ok)
          expect(json_response).to be_an Array
          expect(json_response.length).to eq(0)
        end

        context 'when using all_available in request' do
          it 'returns public descendants' do
            get api("/groups/#{group1.id}/descendant_groups", user2), params: { all_available: true }

            expect(response).to have_gitlab_http_status(:ok)
            expect(json_response).to be_an Array
            expect(json_response.length).to eq(2)
            expect(response_groups).to contain_exactly(child_group1.name, sub_child_group1.name)
          end
        end
      end

      context 'when user is not member of a private group' do
        it 'returns 404 for the private group' do
          get api("/groups/#{group2.id}/descendant_groups", user1)

          expect(response).to have_gitlab_http_status(:not_found)
        end
      end

      context 'when user is member of public group' do
        before do
          group1.add_guest(user2)
        end

        it 'returns private descendants' do
          get api("/groups/#{group1.id}/descendant_groups", user2)

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to include_pagination_headers
          expect(json_response).to be_an Array
          expect(json_response.length).to eq(3)
          expect(response_groups).to contain_exactly(child_group1.name, sub_child_group1.name, private_child_group1.name)
        end

        context 'when using statistics in request' do
          it 'does not include statistics' do
            get api("/groups/#{group1.id}/descendant_groups", user2), params: { statistics: true }

            expect(response).to have_gitlab_http_status(:ok)
            expect(json_response).to be_an Array
            expect(json_response.first).not_to include 'statistics'
          end
        end
      end

      context 'when user is member of private group' do
        before do
          group2.add_guest(user1)
        end

        it 'returns descendants' do
          get api("/groups/#{group2.id}/descendant_groups", user1)

          expect(response).to have_gitlab_http_status(:ok)
          expect(json_response).to be_an Array
          expect(json_response.length).to eq(2)
          expect(response_groups).to contain_exactly(child_group2.name, sub_child_group2.name)
        end
      end
    end

    context 'when authenticated as admin' do
      it 'returns private descendants of a public group' do
        get api("/groups/#{group1.id}/descendant_groups", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(3)
      end

      it 'returns descendants of a private group' do
        get api("/groups/#{group2.id}/descendant_groups", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).to be_an Array
        expect(json_response.length).to eq(2)
      end

      it 'does not include statistics by default' do
        get api("/groups/#{group1.id}/descendant_groups", admin)

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).to be_an Array
        expect(json_response.first).not_to include('statistics')
      end

      it 'includes statistics if requested' do
        get api("/groups/#{group1.id}/descendant_groups", admin), params: { statistics: true }

        expect(response).to have_gitlab_http_status(:ok)
        expect(json_response).to be_an Array
        expect(json_response.first).to include('statistics')
      end
    end
  end

  describe "POST /groups" do
    it_behaves_like 'group avatar upload' do
      def make_upload_request
        params = attributes_for_group_api(request_access_enabled: false).tap do |attrs|
          attrs[:avatar] = fixture_file_upload(file_path)
        end

        post api("/groups", user3), params: params
      end
    end

    context "when authenticated as user without group permissions" do
      it "does not create group" do
        group = attributes_for_group_api

        post api("/groups", user1), params: group

        expect(response).to have_gitlab_http_status(:forbidden)
      end

      context 'as owner' do
        before do
          group2.add_owner(user1)
        end

        it 'can create subgroups' do
          post api("/groups", user1), params: { parent_id: group2.id, name: 'foo', path: 'foo' }

          expect(response).to have_gitlab_http_status(:created)
        end
      end

      context 'as maintainer' do
        before do
          group2.add_maintainer(user1)
        end

        it 'can create subgroups' do
          post api("/groups", user1), params: { parent_id: group2.id, name: 'foo', path: 'foo' }

          expect(response).to have_gitlab_http_status(:created)
        end
      end
    end

    context "when authenticated as user with group permissions" do
      it "creates group" do
        group = attributes_for_group_api request_access_enabled: false

        post api("/groups", user3), params: group

        expect(response).to have_gitlab_http_status(:created)

        expect(json_response["name"]).to eq(group[:name])
        expect(json_response["path"]).to eq(group[:path])
        expect(json_response["request_access_enabled"]).to eq(group[:request_access_enabled])
        expect(json_response["visibility"]).to eq(Gitlab::VisibilityLevel.string_level(Gitlab::CurrentSettings.current_application_settings.default_group_visibility))
      end

      it "creates a nested group" do
        parent = create(:group)
        parent.add_owner(user3)
        group = attributes_for_group_api parent_id: parent.id

        post api("/groups", user3), params: group

        expect(response).to have_gitlab_http_status(:created)

        expect(json_response["full_path"]).to eq("#{parent.path}/#{group[:path]}")
        expect(json_response["parent_id"]).to eq(parent.id)
      end

      context 'malicious group name' do
        subject { post api("/groups", user3), params: group_params }

        let(:group_params) { attributes_for_group_api name: "<SCRIPT>alert('ATTACKED!')</SCRIPT>", path: "unique-url" }

        it 'returns bad request' do
          subject

          expect(response).to have_gitlab_http_status(:bad_request)
        end

        it { expect { subject }.not_to change { Group.count } }
      end

      context 'when creating a group with `default_branch_protection` attribute' do
        let(:params) { attributes_for_group_api default_branch_protection: Gitlab::Access::PROTECTION_NONE }

        subject { post api("/groups", user3), params: params }

        context 'for users who have the ability to create a group with `default_branch_protection`' do
          it 'creates group with the specified branch protection level' do
            subject

            expect(response).to have_gitlab_http_status(:created)
            expect(json_response['default_branch_protection']).to eq(Gitlab::Access::PROTECTION_NONE)
          end
        end

        context 'for users who do not have the ability to create a group with `default_branch_protection`' do
          it 'does not create the group with the specified branch protection level' do
            allow(Ability).to receive(:allowed?).and_call_original
            allow(Ability).to receive(:allowed?).with(user3, :create_group_with_default_branch_protection) { false }

            subject

            expect(response).to have_gitlab_http_status(:created)
            expect(json_response['default_branch_protection']).not_to eq(Gitlab::Access::PROTECTION_NONE)
          end
        end
      end

      it "does not create group, duplicate" do
        post api("/groups", user3), params: { name: 'Duplicate Test', path: group2.path }

        expect(response).to have_gitlab_http_status(:bad_request)
        expect(response.message).to eq("Bad Request")
      end

      it "returns 400 bad request error if name not given" do
        post api("/groups", user3), params: { path: group2.path }

        expect(response).to have_gitlab_http_status(:bad_request)
      end

      it "returns 400 bad request error if path not given" do
        post api("/groups", user3), params: { name: 'test' }

        expect(response).to have_gitlab_http_status(:bad_request)
      end
    end
  end

  describe "DELETE /groups/:id" do
    context "when authenticated as user" do
      it "removes group" do
        Sidekiq::Testing.fake! do
          expect { delete api("/groups/#{group1.id}", user1) }.to change(GroupDestroyWorker.jobs, :size).by(1)
        end

        expect(response).to have_gitlab_http_status(:accepted)
      end

      it_behaves_like '412 response' do
        let(:request) { api("/groups/#{group1.id}", user1) }
        let(:success_status) { 202 }
      end

      it "does not remove a group if not an owner" do
        user4 = create(:user)
        group1.add_maintainer(user4)

        delete api("/groups/#{group1.id}", user3)

        expect(response).to have_gitlab_http_status(:forbidden)
      end

      it "does not remove a non existing group" do
        delete api("/groups/1328", user1)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it "does not remove a group not attached to user1" do
        delete api("/groups/#{group2.id}", user1)

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end

    context "when authenticated as admin" do
      it "removes any existing group" do
        delete api("/groups/#{group2.id}", admin)

        expect(response).to have_gitlab_http_status(:accepted)
      end

      it "does not remove a non existing group" do
        delete api("/groups/1328", admin)

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end
  end

  describe "POST /groups/:id/projects/:project_id" do
    let(:project) { create(:project) }
    let(:project_path) { CGI.escape(project.full_path) }

    before do
      allow_next_instance_of(Projects::TransferService) do |instance|
        allow(instance).to receive(:execute).and_return(true)
      end
    end

    context "when authenticated as user" do
      it "does not transfer project to group" do
        post api("/groups/#{group1.id}/projects/#{project.id}", user2)

        expect(response).to have_gitlab_http_status(:forbidden)
      end
    end

    context "when authenticated as admin" do
      it "transfers project to group" do
        post api("/groups/#{group1.id}/projects/#{project.id}", admin)

        expect(response).to have_gitlab_http_status(:created)
      end

      context 'when using project path in URL' do
        context 'with a valid project path' do
          it "transfers project to group" do
            post api("/groups/#{group1.id}/projects/#{project_path}", admin)

            expect(response).to have_gitlab_http_status(:created)
          end
        end

        context 'with a non-existent project path' do
          it "does not transfer project to group" do
            post api("/groups/#{group1.id}/projects/nogroup%2Fnoproject", admin)

            expect(response).to have_gitlab_http_status(:not_found)
          end
        end
      end

      context 'when using a group path in URL' do
        context 'with a valid group path' do
          it "transfers project to group" do
            post api("/groups/#{group1.path}/projects/#{project_path}", admin)

            expect(response).to have_gitlab_http_status(:created)
          end
        end

        context 'with a non-existent group path' do
          it "does not transfer project to group" do
            post api("/groups/noexist/projects/#{project_path}", admin)

            expect(response).to have_gitlab_http_status(:not_found)
          end
        end
      end
    end
  end

  it_behaves_like 'custom attributes endpoints', 'groups' do
    let(:attributable) { group1 }
    let(:other_attributable) { group2 }
    let(:user) { user1 }

    before do
      group2.add_owner(user1)
    end
  end

  describe "POST /groups/:id/share" do
    shared_examples 'shares group with group' do
      it "shares group with group" do
        expires_at = 10.days.from_now.to_date

        expect do
          post api("/groups/#{group.id}/share", user), params: { group_id: shared_with_group.id, group_access: Gitlab::Access::DEVELOPER, expires_at: expires_at }
        end.to change { group.shared_with_group_links.count }.by(1)

        expect(response).to have_gitlab_http_status(:created)
        expect(json_response['shared_with_groups']).to be_an Array
        expect(json_response['shared_with_groups'].length).to eq(1)
        expect(json_response['shared_with_groups'][0]['group_id']).to eq(shared_with_group.id)
        expect(json_response['shared_with_groups'][0]['group_name']).to eq(shared_with_group.name)
        expect(json_response['shared_with_groups'][0]['group_full_path']).to eq(shared_with_group.full_path)
        expect(json_response['shared_with_groups'][0]['group_access_level']).to eq(Gitlab::Access::DEVELOPER)
        expect(json_response['shared_with_groups'][0]['expires_at']).to eq(expires_at.to_s)
      end

      it "returns a 400 error when group id is not given" do
        post api("/groups/#{group.id}/share", user), params: { group_access: Gitlab::Access::DEVELOPER }
        expect(response).to have_gitlab_http_status(:bad_request)
      end

      it "returns a 400 error when access level is not given" do
        post api("/groups/#{group.id}/share", user), params: { group_id: shared_with_group.id }
        expect(response).to have_gitlab_http_status(:bad_request)
      end

      it 'returns a 404 error when group does not exist' do
        post api("/groups/#{group.id}/share", user), params: { group_id: non_existing_record_id, group_access: Gitlab::Access::DEVELOPER }

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it "returns a 400 error when wrong params passed" do
        post api("/groups/#{group.id}/share", user), params: { group_id: shared_with_group.id, group_access: non_existing_record_access_level }

        expect(response).to have_gitlab_http_status(:bad_request)
        expect(json_response['error']).to eq 'group_access does not have a valid value'
      end

      it "returns a 409 error when link is not saved" do
        allow(::Groups::GroupLinks::CreateService).to receive_message_chain(:new, :execute)
          .and_return({ status: :error, http_status: 409, message: 'error' })

        post api("/groups/#{group.id}/share", user), params: { group_id: shared_with_group.id, group_access: Gitlab::Access::DEVELOPER }

        expect(response).to have_gitlab_http_status(:conflict)
      end
    end

    context 'when authenticated as owner' do
      let(:owner_group) { create(:group) }
      let(:owner_user) { create(:user) }

      before do
        owner_group.add_owner(owner_user)
      end

      it_behaves_like 'shares group with group' do
        let(:user) { owner_user }
        let(:group) { owner_group }
        let(:shared_with_group) { create(:group) }
      end
    end

    context 'when the user is not the owner of the group' do
      let(:group) { create(:group) }
      let(:user4) { create(:user) }
      let(:expires_at) { 10.days.from_now.to_date }

      before do
        group1.add_maintainer(user4)
      end

      it 'does not create group share' do
        post api("/groups/#{group1.id}/share", user4), params: { group_id: group.id, group_access: Gitlab::Access::DEVELOPER, expires_at: expires_at }

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end

    context 'when authenticated as admin' do
      it_behaves_like 'shares group with group' do
        let(:user) { admin }
        let(:group) { create(:group) }
        let(:shared_with_group) { create(:group) }
      end
    end
  end

  describe 'DELETE /groups/:id/share/:group_id' do
    shared_examples 'deletes group share' do
      it 'deletes a group share' do
        expect do
          delete api("/groups/#{shared_group.id}/share/#{shared_with_group.id}", user)

          expect(response).to have_gitlab_http_status(:no_content)
          expect(shared_group.shared_with_group_links).to be_empty
        end.to change { shared_group.shared_with_group_links.count }.by(-1)
      end

      it 'requires the group id to be an integer' do
        delete api("/groups/#{shared_group.id}/share/foo", user)

        expect(response).to have_gitlab_http_status(:bad_request)
      end

      it 'returns a 404 error when group link does not exist' do
        delete api("/groups/#{shared_group.id}/share/#{non_existing_record_id}", user)

        expect(response).to have_gitlab_http_status(:not_found)
      end

      it 'returns a 404 error when group does not exist' do
        delete api("/groups/123/share/#{non_existing_record_id}", user)

        expect(response).to have_gitlab_http_status(:not_found)
      end
    end

    context 'when authenticated as owner' do
      let(:group_a) { create(:group) }

      before do
        create(:group_group_link, shared_group: group1, shared_with_group: group_a)
      end

      it_behaves_like 'deletes group share' do
        let(:user) { user1 }
        let(:shared_group) { group1 }
        let(:shared_with_group) { group_a }
      end
    end

    context 'when the user is not the owner of the group' do
      let(:group_a) { create(:group) }
      let(:user4) { create(:user) }

      before do
        group1.add_maintainer(user4)
        create(:group_group_link, shared_group: group1, shared_with_group: group_a)
      end

      it 'does not remove group share' do
        expect do
          delete api("/groups/#{group1.id}/share/#{group_a.id}", user4)

          expect(response).to have_gitlab_http_status(:no_content)
        end.not_to change { group1.shared_with_group_links }
      end
    end

    context 'when authenticated as admin' do
      let(:group_b) { create(:group) }

      before do
        create(:group_group_link, shared_group: group2, shared_with_group: group_b)
      end

      it_behaves_like 'deletes group share' do
        let(:user) { admin }
        let(:shared_group) { group2 }
        let(:shared_with_group) { group_b }
      end
    end
  end
end