summaryrefslogtreecommitdiff
path: root/spec/controllers/projects/issues_controller_spec.rb
blob: 0c29280316ada946591b2b5a3cbdf44e54659b46 (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
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Projects::IssuesController do
  include ProjectForksHelper
  include_context 'includes Spam constants'

  let_it_be(:project, reload: true) { create(:project) }
  let_it_be(:user, reload: true) { create(:user) }

  let(:issue) { create(:issue, project: project) }
  let(:spam_action_response_fields) { { 'stub_spam_action_response_fields' => true } }

  describe "GET #index" do
    context 'external issue tracker' do
      before do
        sign_in(user)
        project.add_developer(user)
        create(:jira_integration, project: project)
      end

      context 'when GitLab issues disabled' do
        it 'returns 404 status' do
          project.issues_enabled = false
          project.save!

          get :index, params: { namespace_id: project.namespace, project_id: project }

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

      context 'when GitLab issues enabled' do
        it 'renders the "index" template' do
          get :index, params: { namespace_id: project.namespace, project_id: project }

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to render_template(:index)
        end
      end

      context 'when project has moved' do
        let_it_be(:new_project) { create(:project) }
        let_it_be(:issue) { create(:issue, project: new_project) }

        before do
          project.route.destroy!
          new_project.redirect_routes.create!(path: project.full_path)
          new_project.add_developer(user)
        end

        it 'redirects to the new issue tracker from the old one' do
          get :index, params: { namespace_id: project.namespace, project_id: project }

          expect(response).to redirect_to(project_issues_path(new_project))
          expect(response).to have_gitlab_http_status(:moved_permanently)
        end

        it 'redirects from an old issue correctly' do
          get :show, params: { namespace_id: project.namespace, project_id: project, id: issue }

          expect(response).to redirect_to(project_issue_path(new_project, issue))
          expect(response).to have_gitlab_http_status(:moved_permanently)
        end
      end
    end

    context 'internal issue tracker' do
      before do
        sign_in(user)
        project.add_developer(user)
      end

      it_behaves_like "issuables list meta-data", :issue

      it_behaves_like 'set sort order from user preference' do
        let(:sorting_param) { 'updated_asc' }
      end

      it "returns index" do
        get :index, params: { namespace_id: project.namespace, project_id: project }

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

      it 'returns only list type issues' do
        issue = create(:issue, project: project)
        incident = create(:issue, project: project, issue_type: 'incident')
        create(:issue, project: project, issue_type: 'test_case')

        get :index, params: { namespace_id: project.namespace, project_id: project }

        expect(assigns(:issues)).to contain_exactly(issue, incident)
      end

      it "returns 301 if request path doesn't match project path" do
        get :index, params: { namespace_id: project.namespace, project_id: project.path.upcase }

        expect(response).to redirect_to(project_issues_path(project))
      end

      it "returns 404 when issues are disabled" do
        project.issues_enabled = false
        project.save!

        get :index, params: { namespace_id: project.namespace, project_id: project }
        expect(response).to have_gitlab_http_status(:not_found)
      end
    end

    it_behaves_like 'paginated collection' do
      let!(:issue_list) { create_list(:issue, 2, project: project) }
      let(:collection) { project.issues }
      let(:params) do
        {
          namespace_id: project.namespace.to_param,
          project_id: project,
          state: 'opened'
        }
      end

      before do
        sign_in(user)
        project.add_developer(user)
        allow(Kaminari.config).to receive(:default_per_page).and_return(1)
      end

      it 'does not use pagination if disabled' do
        allow(controller).to receive(:pagination_disabled?).and_return(true)

        get :index, params: params.merge(page: last_page + 1)

        expect(response).to have_gitlab_http_status(:ok)
        expect(assigns(:issues).size).to eq(2)
      end
    end

    context 'with relative_position sorting' do
      let!(:issue_list) { create_list(:issue, 2, project: project) }

      before do
        sign_in(user)
        project.add_developer(user)
        allow(Kaminari.config).to receive(:default_per_page).and_return(1)
      end

      it 'overrides the number allowed on the page' do
        get :index,
          params: {
            namespace_id: project.namespace.to_param,
            project_id:   project,
            sort:         'relative_position'
          }

        expect(assigns(:issues).count).to eq 2
      end

      it 'allows the default number on the page' do
        get :index,
          params: {
            namespace_id: project.namespace.to_param,
            project_id:   project
          }

        expect(assigns(:issues).count).to eq 1
      end
    end

    context 'external authorization' do
      before do
        sign_in user
        project.add_developer(user)
      end

      it_behaves_like 'unauthorized when external service denies access' do
        subject { get :index, params: { namespace_id: project.namespace, project_id: project } }
      end
    end
  end

  describe "GET #show" do
    before do
      sign_in(user)
      project.add_developer(user)
    end

    it "returns issue_email_participants" do
      participants = create_list(:issue_email_participant, 2, issue: issue)

      get :show, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }, format: :json

      expect(response).to have_gitlab_http_status(:ok)
      expect(json_response['issue_email_participants']).to contain_exactly({ "email" => participants[0].email }, { "email" => participants[1].email })
    end

    context 'with the invite_members_in_comment experiment', :experiment do
      context 'when user can invite' do
        before do
          stub_experiments(invite_members_in_comment: :invite_member_link)
          project.add_maintainer(user)
        end

        it 'assigns the candidate experience and tracks the event' do
          expect(experiment(:invite_members_in_comment)).to track(:view, property: project.root_ancestor.id.to_s)
            .for(:invite_member_link)
            .with_context(namespace: project.root_ancestor)
            .on_next_instance

          get :show, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }
        end
      end

      context 'when user can not invite' do
        it 'does not track the event' do
          expect(experiment(:invite_members_in_comment)).not_to track(:view)

          get :show, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }
        end
      end
    end
  end

  describe 'GET #new' do
    it 'redirects to signin if not logged in' do
      get :new, params: { namespace_id: project.namespace, project_id: project }

      expect(flash[:alert]).to eq I18n.t('devise.failure.unauthenticated')
      expect(response).to redirect_to(new_user_session_path)
    end

    context 'internal issue tracker' do
      before do
        sign_in(user)
        project.add_developer(user)
      end

      it 'builds a new issue', :aggregate_failures do
        get :new, params: { namespace_id: project.namespace, project_id: project }

        expect(assigns(:issue)).to be_a_new(Issue)
        expect(assigns(:issue).issue_type).to eq('issue')
      end

      where(:conf_value, :conf_result) do
        [
          [true, true],
          ['true', true],
          ['TRUE', true],
          [false, false],
          ['false', false],
          ['FALSE', false]
        ]
      end

      with_them do
        it 'sets the confidential flag to the expected value' do
          get :new, params: {
            namespace_id: project.namespace,
            project_id: project,
            issue: {
              confidential: conf_value
            }
          }

          assigned_issue = assigns(:issue)
          expect(assigned_issue).to be_a_new(Issue)
          expect(assigned_issue.confidential).to eq conf_result
        end
      end

      context 'setting issue type' do
        let(:issue_type) { 'issue' }

        before do
          get :new, params: { namespace_id: project.namespace, project_id: project, issue: { issue_type: issue_type } }
        end

        subject { assigns(:issue).issue_type }

        it { is_expected.to eq('issue') }

        context 'incident issue' do
          let(:issue_type) { 'incident' }

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

      it 'fills in an issue for a merge request' do
        project_with_repository = create(:project, :repository)
        project_with_repository.add_developer(user)
        mr = create(:merge_request_with_diff_notes, source_project: project_with_repository)

        get :new, params: { namespace_id: project_with_repository.namespace, project_id: project_with_repository, merge_request_to_resolve_discussions_of: mr.iid }

        expect(assigns(:issue).title).not_to be_empty
        expect(assigns(:issue).description).not_to be_empty
      end

      it 'fills in an issue for a discussion' do
        note = create(:note_on_merge_request, project: project)

        get :new, params: { namespace_id: project.namespace.path, project_id: project, merge_request_to_resolve_discussions_of: note.noteable.iid, discussion_to_resolve: note.discussion_id }

        expect(assigns(:issue).title).not_to be_empty
        expect(assigns(:issue).description).not_to be_empty
      end
    end

    context 'external issue tracker' do
      let!(:service) do
        create(:custom_issue_tracker_integration, project: project, new_issue_url: 'http://test.com')
      end

      before do
        sign_in(user)
        project.add_developer(user)

        external = double
        allow(project).to receive(:external_issue_tracker).and_return(external)
      end

      context 'when GitLab issues disabled' do
        it 'returns 404 status' do
          project.issues_enabled = false
          project.save!

          get :new, params: { namespace_id: project.namespace, project_id: project }

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

      context 'when GitLab issues enabled' do
        it 'renders the "new" template' do
          get :new, params: { namespace_id: project.namespace, project_id: project }

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to render_template(:new)
        end
      end
    end
  end

  describe '#related_branches' do
    subject { get :related_branches, params: params, format: :json }

    before do
      sign_in(user)
      project.add_developer(developer)
    end

    let_it_be(:issue) { create(:issue, project: project) }

    let(:developer) { user }
    let(:params) do
      {
        namespace_id: project.namespace,
        project_id: project,
        id: issue.iid
      }
    end

    context 'the current user cannot download code' do
      it 'prevents access' do
        allow(controller).to receive(:can?).with(any_args).and_return(true)
        allow(controller).to receive(:can?).with(user, :download_code, project).and_return(false)

        subject

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

    context 'there are no related branches' do
      it 'assigns empty arrays', :aggregate_failures do
        subject

        expect(response).to have_gitlab_http_status(:ok)
        expect(assigns(:related_branches)).to be_empty
        expect(response).to render_template('projects/issues/_related_branches')
        expect(json_response).to eq('html' => '')
      end
    end

    context 'there are related branches' do
      let(:missing_branch) { "#{issue.to_branch_name}-missing" }
      let(:unreadable_branch) { "#{issue.to_branch_name}-unreadable" }
      let(:pipeline) { build(:ci_pipeline, :success, project: project) }
      let(:master_branch) { 'master' }

      let(:related_branches) do
        [
          branch_info(issue.to_branch_name, pipeline.detailed_status(user)),
          branch_info(missing_branch, nil),
          branch_info(unreadable_branch, nil)
        ]
      end

      def branch_info(name, status)
        {
          name: name,
          link: controller.project_compare_path(project, from: master_branch, to: name),
          pipeline_status: status
        }
      end

      before do
        allow(controller).to receive(:find_routable!).and_return(project)
        allow(project).to receive(:default_branch).and_return(master_branch)
        allow_next_instance_of(Issues::RelatedBranchesService) do |service|
          allow(service).to receive(:execute).and_return(related_branches)
        end
      end

      it 'finds and assigns the appropriate branch information', :aggregate_failures do
        subject

        expect(response).to have_gitlab_http_status(:ok)
        expect(assigns(:related_branches)).to contain_exactly(
          branch_info(issue.to_branch_name, an_instance_of(Gitlab::Ci::Status::Success)),
          branch_info(missing_branch, be_nil),
          branch_info(unreadable_branch, be_nil)
        )
        expect(response).to render_template('projects/issues/_related_branches')
        expect(json_response).to match('html' => String)
      end
    end
  end

  # This spec runs as a request-style spec in order to invoke the
  # Rails router. A controller-style spec matches the wrong route, and
  # session['user_return_to'] becomes incorrect.
  describe 'Redirect after sign in', type: :request do
    before_all do
      project.add_developer(user)
    end

    before do
      login_as(user)
    end

    context 'with a JSON request' do
      it 'does not store the visited URL' do
        get project_issue_path(project, issue, format: :json)

        expect(session['user_return_to']).to be_blank
      end
    end

    context 'with an HTML request' do
      it 'stores the visited URL' do
        get project_issue_path(project, issue)

        expect(session['user_return_to']).to eq(project_issue_path(project, issue))
      end
    end
  end

  describe 'POST #move' do
    before do
      sign_in(user)
      project.add_developer(user)
    end

    context 'when moving issue to another private project' do
      let_it_be(:another_project) { create(:project, :private) }

      context 'when user has access to move issue' do
        before do
          another_project.add_reporter(user)
        end

        it 'moves issue to another project' do
          move_issue

          expect(response).to have_gitlab_http_status :ok
          expect(another_project.issues).not_to be_empty
        end
      end

      context 'when user does not have access to move issue' do
        it 'responds with 404' do
          move_issue

          expect(response).to have_gitlab_http_status :not_found
        end
      end

      def move_issue
        post :move,
          params: {
            namespace_id: project.namespace.to_param,
            project_id: project,
            id: issue.iid,
            move_to_project_id: another_project.id
          },
          format: :json
      end
    end
  end

  describe 'PUT #reorder' do
    let_it_be(:group)  { create(:group, projects: [project]) }
    let_it_be(:issue1) { create(:issue, project: project, relative_position: 10) }
    let_it_be(:issue2) { create(:issue, project: project, relative_position: 20) }
    let_it_be(:issue3) { create(:issue, project: project, relative_position: 30) }

    before do
      sign_in(user)
    end

    context 'when user has access' do
      before do
        project.add_developer(user)
      end

      context 'with valid params' do
        it 'reorders issues and returns a successful 200 response' do
          reorder_issue(issue1,
            move_after_id: issue2.id,
            move_before_id: issue3.id,
            group_full_path: group.full_path)

          [issue1, issue2, issue3].map(&:reload)

          expect(response).to have_gitlab_http_status(:ok)
          expect(issue1.relative_position)
            .to be_between(issue2.relative_position, issue3.relative_position)
        end
      end

      context 'with invalid params' do
        it 'returns a unprocessable entity 422 response for invalid move ids' do
          reorder_issue(issue1, move_after_id: 99, move_before_id: non_existing_record_id)

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

        it 'returns a not found 404 response for invalid issue id' do
          reorder_issue(object_double(issue1, iid: non_existing_record_iid),
            move_after_id: issue2.id,
            move_before_id: issue3.id)

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

        it 'returns a unprocessable entity 422 response for issues not in group' do
          another_group = create(:group)

          reorder_issue(issue1,
            move_after_id: issue2.id,
            move_before_id: issue3.id,
            group_full_path: another_group.full_path)

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

    context 'with unauthorized user' do
      before do
        project.add_guest(user)
      end

      it 'responds with 404' do
        reorder_issue(issue1, move_after_id: issue2.id, move_before_id: issue3.id)

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

    def reorder_issue(issue, move_after_id: nil, move_before_id: nil, group_full_path: nil)
      put :reorder,
           params: {
               namespace_id: project.namespace.to_param,
               project_id: project,
               id: issue.iid,
               move_after_id: move_after_id,
               move_before_id: move_before_id,
               group_full_path: group_full_path
           },
           format: :json
    end
  end

  describe 'PUT #update' do
    let(:issue_params) { { title: 'New title' } }

    subject do
      put :update,
        params: {
          namespace_id: project.namespace,
          project_id: project,
          id: issue.to_param,
          issue: issue_params
        },
        format: :json
    end

    before do
      sign_in(user)
    end

    context 'when user has access to update issue' do
      before do
        project.update!(visibility_level: Gitlab::VisibilityLevel::PUBLIC)
        project.add_developer(user)
      end

      it 'updates the issue' do
        subject

        expect(response).to have_gitlab_http_status(:ok)
        expect(issue.reload.title).to eq('New title')
      end

      context 'with issue_type param' do
        let(:issue_params) { { issue_type: 'incident' } }

        it 'permits the parameter' do
          subject

          expect(response).to have_gitlab_http_status(:ok)
          expect(issue.reload.issue_type).to eql('incident')
        end
      end

      context 'when the SpamVerdictService disallows' do
        before do
          stub_application_setting(recaptcha_enabled: true)
          expect_next_instance_of(Spam::SpamVerdictService) do |verdict_service|
            expect(verdict_service).to receive(:execute).and_return(CONDITIONAL_ALLOW)
          end
        end

        context 'when allow_possible_spam feature flag is false' do
          before do
            stub_feature_flags(allow_possible_spam: false)
            expect(controller).to(receive(:spam_action_response_fields).with(issue)) do
              spam_action_response_fields
            end
          end

          it 'renders json with spam_action_response_fields' do
            subject

            expect(json_response).to eq(spam_action_response_fields)
          end
        end

        context 'when allow_possible_spam feature flag is true' do
          it 'updates the issue' do
            subject

            expect(response).to have_gitlab_http_status(:ok)
            expect(issue.reload.title).to eq('New title')
          end
        end
      end
    end

    context 'when user does not have access to update issue' do
      before do
        project.add_guest(user)
      end

      it 'responds with 404' do
        subject

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

  describe 'GET #realtime_changes' do
    def go(id:)
      get :realtime_changes,
        params: {
          namespace_id: project.namespace.to_param,
          project_id: project,
          id: id
        }
    end

    context 'when an issue was edited' do
      before do
        project.add_developer(user)

        issue.update!(last_edited_by: user, last_edited_at: issue.created_at + 1.minute)

        sign_in(user)
      end

      it 'returns last edited time' do
        go(id: issue.iid)

        expect(json_response).to include('updated_at')
        expect(json_response['updated_at']).to eq(issue.last_edited_at.to_time.iso8601)
      end
    end

    context 'when an issue was edited by a deleted user' do
      let(:deleted_user) { create(:user) }

      before do
        project.add_developer(user)

        issue.update!(last_edited_by: deleted_user, last_edited_at: Time.current)

        deleted_user.destroy!
        sign_in(user)
      end

      it 'returns 200' do
        go(id: issue.iid)

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

    context 'when getting the changes' do
      before do
        project.add_developer(user)

        sign_in(user)
      end

      it 'returns the necessary data' do
        go(id: issue.iid)

        expect(json_response).to include('title_text', 'description', 'description_text')
        expect(json_response).to include('task_status', 'lock_version')
      end
    end
  end

  describe 'Confidential Issues' do
    let_it_be(:project) { create(:project_empty_repo, :public) }
    let_it_be(:assignee) { create(:assignee) }
    let_it_be(:author) { create(:user) }
    let_it_be(:non_member) { create(:user) }
    let_it_be(:member) { create(:user) }
    let_it_be(:admin) { create(:admin) }
    let_it_be(:issue) { create(:issue, project: project) }
    let_it_be(:unescaped_parameter_value) { create(:issue, :confidential, project: project, author: author) }
    let_it_be(:request_forgery_timing_attack) { create(:issue, :confidential, project: project, assignees: [assignee]) }

    describe 'GET #index' do
      it 'does not list confidential issues for guests' do
        sign_out(:user)
        get_issues

        expect(assigns(:issues)).to eq [issue]
      end

      it 'does not list confidential issues for non project members' do
        sign_in(non_member)
        get_issues

        expect(assigns(:issues)).to eq [issue]
      end

      it 'does not list confidential issues for project members with guest role' do
        sign_in(member)
        project.add_guest(member)

        get_issues

        expect(assigns(:issues)).to eq [issue]
      end

      it 'lists confidential issues for author' do
        sign_in(author)
        get_issues

        expect(assigns(:issues)).to include unescaped_parameter_value
        expect(assigns(:issues)).not_to include request_forgery_timing_attack
      end

      it 'lists confidential issues for assignee' do
        sign_in(assignee)
        get_issues

        expect(assigns(:issues)).not_to include unescaped_parameter_value
        expect(assigns(:issues)).to include request_forgery_timing_attack
      end

      it 'lists confidential issues for project members' do
        sign_in(member)
        project.add_developer(member)

        get_issues

        expect(assigns(:issues)).to include unescaped_parameter_value
        expect(assigns(:issues)).to include request_forgery_timing_attack
      end

      context 'when admin mode is enabled', :enable_admin_mode do
        it 'lists confidential issues for admin' do
          sign_in(admin)
          get_issues

          expect(assigns(:issues)).to include unescaped_parameter_value
          expect(assigns(:issues)).to include request_forgery_timing_attack
        end
      end

      context 'when admin mode is disabled' do
        it 'does not list confidential issues for admin' do
          sign_in(admin)
          get_issues

          expect(assigns(:issues)).to eq [issue]
        end
      end

      def get_issues
        get :index,
          params: {
            namespace_id: project.namespace.to_param,
            project_id: project
          }
      end
    end

    shared_examples_for 'restricted action' do |http_status|
      it 'returns 404 for guests' do
        sign_out(:user)
        go(id: unescaped_parameter_value.to_param)

        expect(response).to have_gitlab_http_status :not_found
      end

      it 'returns 404 for non project members' do
        sign_in(non_member)
        go(id: unescaped_parameter_value.to_param)

        expect(response).to have_gitlab_http_status :not_found
      end

      it 'returns 404 for project members with guest role' do
        sign_in(member)
        project.add_guest(member)
        go(id: unescaped_parameter_value.to_param)

        expect(response).to have_gitlab_http_status :not_found
      end

      it "returns #{http_status[:success]} for author" do
        sign_in(author)
        go(id: unescaped_parameter_value.to_param)

        expect(response).to have_gitlab_http_status http_status[:success]
      end

      it "returns #{http_status[:success]} for assignee" do
        sign_in(assignee)
        go(id: request_forgery_timing_attack.to_param)

        expect(response).to have_gitlab_http_status http_status[:success]
      end

      it "returns #{http_status[:success]} for project members" do
        sign_in(member)
        project.add_developer(member)
        go(id: unescaped_parameter_value.to_param)

        expect(response).to have_gitlab_http_status http_status[:success]
      end

      context 'when admin mode is enabled', :enable_admin_mode do
        it "returns #{http_status[:success]} for admin" do
          sign_in(admin)
          go(id: unescaped_parameter_value.to_param)

          expect(response).to have_gitlab_http_status http_status[:success]
        end
      end

      context 'when admin mode is disabled' do
        xit 'returns 404 for admin' do
          sign_in(admin)
          go(id: unescaped_parameter_value.to_param)

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

    describe 'PUT #update' do
      def update_issue(issue_params: {}, additional_params: {}, id: nil)
        id ||= issue.iid
        params = {
          namespace_id: project.namespace.to_param,
          project_id: project,
          id: id,
          issue: { title: 'New title' }.merge(issue_params),
          format: :json
        }.merge(additional_params)

        put :update, params: params
      end

      def go(id:)
        update_issue(id: id)
      end

      before do
        sign_in(user)
        project.add_developer(user)
      end

      it_behaves_like 'restricted action', success: 200
      it_behaves_like 'update invalid issuable', Issue

      context 'changing the assignee' do
        it 'limits the attributes exposed on the assignee' do
          assignee = create(:user)
          project.add_developer(assignee)

          update_issue(issue_params: { assignee_ids: [assignee.id] })

          expect(json_response['assignees'].first.keys)
            .to include(*%w(id name username avatar_url state web_url))
        end
      end

      context 'Recaptcha is enabled' do
        before do
          project.update!(visibility_level: Gitlab::VisibilityLevel::PUBLIC)
          stub_application_setting(recaptcha_enabled: true)
        end

        context 'when SpamVerdictService allows the issue' do
          before do
            expect_next_instance_of(Spam::SpamVerdictService) do |verdict_service|
              expect(verdict_service).to receive(:execute).and_return(ALLOW)
            end
          end

          it 'normally updates the issue' do
            expect { update_issue(issue_params: { title: 'Foo' }) }.to change { issue.reload.title }.to('Foo')
          end
        end

        context 'when an issue is identified as spam' do
          context 'when recaptcha is not verified' do
            before do
              expect_next_instance_of(Spam::SpamVerdictService) do |verdict_service|
                expect(verdict_service).to receive(:execute).and_return(CONDITIONAL_ALLOW)
              end
            end

            context 'when allow_possible_spam feature flag is false' do
              before do
                stub_feature_flags(allow_possible_spam: false)
              end

              it 'rejects an issue recognized as spam' do
                expect { update_issue }.not_to change { issue.reload.title }
              end

              it 'rejects an issue recognized as a spam when reCAPTCHA disabled' do
                stub_application_setting(recaptcha_enabled: false)

                expect { update_issue }.not_to change { issue.reload.title }
              end

              it 'creates a spam log' do
                expect { update_issue(issue_params: { title: 'Spam title' }) }
                  .to log_spam(title: 'Spam title', noteable_type: 'Issue')
              end

              context 'renders properly' do
                render_views

                before do
                  expect(controller).to(receive(:spam_action_response_fields).with(issue)) do
                    spam_action_response_fields
                  end
                end

                it 'renders spam_action_response_fields json response' do
                  update_issue

                  expect(response).to have_gitlab_http_status(:conflict)
                  expect(json_response).to eq(spam_action_response_fields)
                end
              end
            end

            context 'when allow_possible_spam feature flag is true' do
              it 'updates the issue recognized as spam' do
                expect { update_issue }.to change { issue.reload.title }
              end

              it 'creates a spam log' do
                expect { update_issue(issue_params: { title: 'Spam title' }) }
                  .to log_spam(
                    title: 'Spam title', description: issue.description,
                    noteable_type: 'Issue', recaptcha_verified: false
                  )
              end

              it 'returns 200 status' do
                update_issue

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

          context 'when recaptcha is verified' do
            let(:spammy_title) { 'Whatever' }
            let!(:spam_logs) { create_list(:spam_log, 2, user: user, title: spammy_title) }

            before do
              request.headers['X-GitLab-Captcha-Response'] = 'a-valid-captcha-response'
              request.headers['X-GitLab-Spam-Log-Id'] = spam_logs.last.id
            end

            def update_verified_issue
              update_issue(issue_params: { title: spammy_title })
            end

            it 'returns 200 status' do
              expect(response).to have_gitlab_http_status(:ok)
            end

            it 'accepts an issue after reCAPTCHA is verified' do
              expect { update_verified_issue }.to change { issue.reload.title }.to(spammy_title)
            end

            it 'marks spam log as recaptcha_verified' do
              expect { update_verified_issue }.to change { SpamLog.last.recaptcha_verified }.from(false).to(true)
            end

            it 'does not mark spam log as recaptcha_verified when it does not belong to current_user' do
              spam_log = create(:spam_log)
              request.headers['X-GitLab-Spam-Log-Id'] = spam_log.id

              expect { update_issue }
                .not_to change { SpamLog.last.recaptcha_verified }
            end
          end
        end
      end
    end

    describe 'GET #show' do
      it_behaves_like 'restricted action', success: 200

      def go(id:)
        get :show,
          params: {
            namespace_id: project.namespace.to_param,
            project_id: project,
            id: id
          }
      end

      it 'avoids (most) N+1s loading labels', :request_store do
        label = create(:label, project: project).to_reference
        labels = create_list(:label, 10, project: project).map(&:to_reference)
        issue = create(:issue, project: project, description: 'Test issue')

        control_count = ActiveRecord::QueryRecorder.new { issue.update!(description: [issue.description, label].join(' ')) }.count

        # Follow-up to get rid of this `2 * label.count` requirement: https://gitlab.com/gitlab-org/gitlab-foss/issues/52230
        expect { issue.update!(description: [issue.description, labels].join(' ')) }
          .not_to exceed_query_limit(control_count + 2 * labels.count)
      end

      context 'real-time sidebar feature flag' do
        using RSpec::Parameterized::TableSyntax

        let_it_be(:project) { create(:project, :public) }
        let_it_be(:issue) { create(:issue, project: project) }

        where(:action_cable_in_app_enabled, :feature_flag_enabled, :gon_feature_flag) do
          true  | true  | true
          true  | false | true
          false | true  | true
          false | false | false
        end

        with_them do
          before do
            expect(Gitlab::ActionCable::Config).to receive(:in_app?).and_return(action_cable_in_app_enabled)
            stub_feature_flags(real_time_issue_sidebar: feature_flag_enabled)
          end

          it 'broadcasts to the issues channel based on ActionCable and feature flag values' do
            go(id: issue.to_param)

            expect(Gon.features).to include('realTimeIssueSidebar' => gon_feature_flag)
          end
        end
      end

      it 'logs the view with Gitlab::Search::RecentIssues' do
        sign_in(user)
        recent_issues_double = instance_double(::Gitlab::Search::RecentIssues, log_view: nil)
        expect(::Gitlab::Search::RecentIssues).to receive(:new).with(user: user).and_return(recent_issues_double)

        go(id: issue.to_param)

        expect(response).to be_successful
        expect(recent_issues_double).to have_received(:log_view).with(issue)
      end

      context 'when not logged in' do
        it 'does not log the view with Gitlab::Search::RecentIssues' do
          expect(::Gitlab::Search::RecentIssues).not_to receive(:new)

          go(id: issue.to_param)
        end
      end
    end

    describe 'GET #realtime_changes' do
      it_behaves_like 'restricted action', success: 200

      def go(id:)
        get :realtime_changes,
          params: {
            namespace_id: project.namespace.to_param,
            project_id: project,
            id: id
          }
      end
    end

    describe 'GET #edit' do
      it_behaves_like 'restricted action', success: 200

      def go(id:)
        get :edit,
          params: {
            namespace_id: project.namespace.to_param,
            project_id: project,
            id: id
          }
      end
    end

    describe 'PUT #update' do
      it_behaves_like 'restricted action', success: 302

      def go(id:)
        put :update,
          params: {
            namespace_id: project.namespace.to_param,
            project_id: project,
            id: id,
            issue: { title: 'New title' }
          }
      end
    end
  end

  describe 'POST #create' do
    def post_new_issue(issue_attrs = {}, additional_params = {})
      sign_in(user)
      project = create(:project, :public)
      project.add_developer(user)

      post :create, params: {
        namespace_id: project.namespace.to_param,
        project_id: project,
        issue: { title: 'Title', description: 'Description' }.merge(issue_attrs)
      }.merge(additional_params)

      project.issues.first
    end

    it 'creates the issue successfully', :aggregate_failures do
      issue = post_new_issue

      expect(issue).to be_a(Issue)
      expect(issue.persisted?).to eq(true)
      expect(issue.issue_type).to eq('issue')
    end

    context 'resolving discussions in MergeRequest' do
      let_it_be(:discussion) { create(:diff_note_on_merge_request).to_discussion }

      let(:merge_request) { discussion.noteable }
      let(:project) { merge_request.source_project }

      before do
        project.add_maintainer(user)
        sign_in user
      end

      let(:merge_request_params) do
        { merge_request_to_resolve_discussions_of: merge_request.iid }
      end

      def post_issue(other_params: {}, **issue_params)
        post :create, params: { namespace_id: project.namespace.to_param, project_id: project, issue: issue_params, merge_request_to_resolve_discussions_of: merge_request.iid }.merge(other_params)
      end

      it 'creates an issue for the project' do
        expect { post_issue(title: 'Hello') }.to change { project.issues.reload.size }.by(1)
      end

      it "doesn't overwrite given params" do
        post_issue(description: 'Manually entered description')

        expect(assigns(:issue).description).to eq('Manually entered description')
      end

      it 'resolves the discussion in the merge_request' do
        post_issue(title: 'Hello')
        discussion.first_note.reload

        expect(discussion.resolved?).to eq(true)
      end

      it 'sets a flash message' do
        post_issue(title: 'Hello')

        expect(flash[:notice]).to eq(_('Resolved all discussions.'))
      end

      describe "resolving a single discussion" do
        before do
          post_issue(title: 'Hello', other_params: { discussion_to_resolve: discussion.id })
        end
        it 'resolves a single discussion' do
          discussion.first_note.reload

          expect(discussion.resolved?).to eq(true)
        end

        it 'sets a flash message that one discussion was resolved' do
          expect(flash[:notice]).to eq(_('Resolved 1 discussion.'))
        end
      end
    end

    context 'Recaptcha is enabled' do
      before do
        stub_application_setting(recaptcha_enabled: true)
      end

      context 'when SpamVerdictService allows the issue' do
        before do
          stub_feature_flags(allow_possible_spam: false)

          expect_next_instance_of(Spam::SpamVerdictService) do |verdict_service|
            expect(verdict_service).to receive(:execute).and_return(ALLOW)
          end
        end

        it 'creates an issue' do
          expect { post_new_issue(title: 'Some title') }.to change(Issue, :count)
        end
      end

      context 'when SpamVerdictService requires recaptcha' do
        context 'when captcha is not verified' do
          before do
            expect_next_instance_of(Spam::SpamVerdictService) do |verdict_service|
              expect(verdict_service).to receive(:execute).and_return(CONDITIONAL_ALLOW)
            end
          end

          def post_spam_issue
            post_new_issue(title: 'Spam Title', description: 'Spam lives here')
          end

          context 'when allow_possible_spam feature flag is false' do
            before do
              stub_feature_flags(allow_possible_spam: false)
            end

            it 'rejects an issue recognized as spam' do
              expect { post_spam_issue }.not_to change(Issue, :count)
            end

            it 'creates a spam log' do
              expect { post_spam_issue }
                .to log_spam(title: 'Spam Title', noteable_type: 'Issue', recaptcha_verified: false)
            end

            it 'does not create an issue when it is not valid' do
              expect { post_new_issue(title: '') }.not_to change(Issue, :count)
            end

            it 'does not create an issue when reCAPTCHA is not enabled' do
              stub_application_setting(recaptcha_enabled: false)

              expect { post_spam_issue }.not_to change(Issue, :count)
            end
          end

          context 'when allow_possible_spam feature flag is true' do
            it 'creates an issue recognized as spam' do
              expect { post_spam_issue }.to change(Issue, :count)
            end

            it 'creates a spam log' do
              expect { post_spam_issue }
                .to log_spam(title: 'Spam Title', noteable_type: 'Issue', recaptcha_verified: false)
            end

            it 'does not create an issue when it is not valid' do
              expect { post_new_issue(title: '') }.not_to change(Issue, :count)
            end
          end
        end

        context 'when Recaptcha is verified' do
          let!(:spam_logs) { create_list(:spam_log, 2, user: user, title: 'Title') }
          let!(:last_spam_log) { spam_logs.last }

          def post_verified_issue
            post_new_issue({}, { spam_log_id: last_spam_log.id, 'g-recaptcha-response': 'abc123' } )
          end

          before do
            expect_next_instance_of(Captcha::CaptchaVerificationService) do |instance|
              expect(instance).to receive(:execute) { true }
            end
          end

          it 'accepts an issue after reCAPTCHA is verified' do
            expect { post_verified_issue }.to change(Issue, :count)
          end

          it 'marks spam log as recaptcha_verified' do
            expect { post_verified_issue }.to change { last_spam_log.reload.recaptcha_verified }.from(false).to(true)
          end

          it 'does not mark spam log as recaptcha_verified when it does not belong to current_user' do
            spam_log = create(:spam_log)

            expect { post_new_issue({}, { spam_log_id: spam_log.id, 'g-recaptcha-response': true } ) }
              .not_to change { last_spam_log.recaptcha_verified }
          end
        end
      end
    end

    context 'user agent details are saved' do
      before do
        request.env['action_dispatch.remote_ip'] = '127.0.0.1'
      end

      it 'creates a user agent detail' do
        expect { post_new_issue }.to change(UserAgentDetail, :count).by(1)
      end
    end

    context 'when description has quick actions' do
      before do
        sign_in(user)
      end

      it 'can add spent time' do
        issue = post_new_issue(description: '/spend 1h')

        expect(issue.total_time_spent).to eq(3600)
      end

      it 'can set the time estimate' do
        issue = post_new_issue(description: '/estimate 2h')

        expect(issue.time_estimate).to eq(7200)
      end
    end

    context 'when created from sentry error' do
      subject { post_new_issue(sentry_issue_attributes: { sentry_issue_identifier: 1234567 }) }

      it 'creates an issue' do
        expect { subject }.to change(Issue, :count)
      end

      it 'creates a sentry issue' do
        expect { subject }.to change(SentryIssue, :count)
      end
    end

    context 'when the endpoint receives requests above the limit' do
      before do
        stub_application_setting(issues_create_limit: 5)
      end

      it 'prevents from creating more issues', :request_store do
        5.times { post_new_issue }

        expect { post_new_issue }
          .to change { Gitlab::GitalyClient.get_request_count }.by(1) # creates 1 projects and 0 issues

        post_new_issue
        expect(response.body).to eq(_('This endpoint has been requested too many times. Try again later.'))
        expect(response).to have_gitlab_http_status(:too_many_requests)
      end

      it 'logs the event on auth.log' do
        attributes = {
          message: 'Application_Rate_Limiter_Request',
          env: :issues_create_request_limit,
          remote_ip: '0.0.0.0',
          request_method: 'POST',
          path: "/#{project.full_path}/-/issues",
          user_id: user.id,
          username: user.username
        }

        expect(Gitlab::AuthLogger).to receive(:error).with(attributes).once

        project.add_developer(user)
        sign_in(user)

        6.times do
          post :create, params: {
            namespace_id: project.namespace.to_param,
            project_id: project,
            issue: { title: 'Title', description: 'Description' }
          }
        end
      end
    end

    context 'setting issue type' do
      let(:issue_type) { 'issue' }

      subject { post_new_issue(issue_type: issue_type)&.issue_type }

      it { is_expected.to eq('issue') }

      context 'incident issue' do
        let(:issue_type) { 'incident' }

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

  describe 'POST #mark_as_spam' do
    context 'properly submits to Akismet' do
      before do
        expect_next_instance_of(Spam::AkismetService) do |akismet_service|
          expect(akismet_service).to receive_messages(submit_spam: true)
        end
        stub_application_setting(akismet_enabled: true)
      end

      def post_spam
        admin = create(:admin)
        create(:user_agent_detail, subject: issue)
        project.add_maintainer(admin)
        sign_in(admin)
        post :mark_as_spam, params: {
          namespace_id: project.namespace,
          project_id: project,
          id: issue.iid
        }
      end

      it 'updates issue', :enable_admin_mode do
        post_spam
        expect(issue.submittable_as_spam?).to be_falsey
      end
    end
  end

  describe "DELETE #destroy" do
    context "when the user is a developer" do
      before do
        sign_in(user)
      end

      it "does not delete the issue, returning :not_found" do
        delete :destroy, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }

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

    context "when the user is owner" do
      let_it_be(:owner)     { create(:user) }
      let_it_be(:namespace) { create(:namespace, owner: owner) }
      let_it_be(:project)   { create(:project, namespace: namespace) }

      before do
        sign_in(owner)
      end

      it "deletes the issue" do
        delete :destroy, params: { namespace_id: project.namespace, project_id: project, id: issue.iid, destroy_confirm: true }

        expect(response).to have_gitlab_http_status(:found)
        expect(controller).to set_flash[:notice].to(/The issue was successfully deleted\./)
      end

      it "prevents deletion if destroy_confirm is not set" do
        expect(Gitlab::ErrorTracking).to receive(:track_exception).and_call_original

        delete :destroy, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }

        expect(response).to have_gitlab_http_status(:found)
        expect(controller).to set_flash[:notice].to('Destroy confirmation not provided for issue')
      end

      it "prevents deletion in JSON format if destroy_confirm is not set" do
        expect(Gitlab::ErrorTracking).to receive(:track_exception).and_call_original

        delete :destroy, params: { namespace_id: project.namespace, project_id: project, id: issue.iid, format: 'json' }

        expect(response).to have_gitlab_http_status(:unprocessable_entity)
        expect(json_response).to eq({ 'errors' => 'Destroy confirmation not provided for issue' })
      end
    end
  end

  describe 'POST #toggle_award_emoji' do
    before do
      sign_in(user)
      project.add_developer(user)
    end

    subject do
      post(:toggle_award_emoji, params: {
        namespace_id: project.namespace,
        project_id: project,
        id: issue.iid,
        name: emoji_name
      })
    end

    let(:emoji_name) { 'thumbsup' }

    it "toggles the award emoji" do
      expect do
        subject
      end.to change { issue.award_emoji.count }.by(1)

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

    it "removes the already awarded emoji" do
      create(:award_emoji, awardable: issue, name: emoji_name, user: user)

      expect { subject }.to change { AwardEmoji.count }.by(-1)

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

    it 'marks Todos on the Issue as done' do
      todo = create(:todo, target: issue, project: project, user: user)

      subject

      expect(todo.reload).to be_done
    end
  end

  describe 'POST create_merge_request' do
    let(:target_project_id) { nil }

    let_it_be(:project) { create(:project, :repository, :public) }

    before do
      project.add_developer(user)
      sign_in(user)
    end

    it 'creates a new merge request' do
      expect { create_merge_request }.to change(project.merge_requests, :count).by(1)
    end

    it 'render merge request as json' do
      create_merge_request

      expect(response).to have_gitlab_http_status(:ok)
      expect(response).to match_response_schema('merge_request')
    end

    it 'is not available when the project is archived' do
      project.update!(archived: true)

      create_merge_request

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

    it 'is not available for users who cannot create merge requests' do
      sign_in(create(:user))

      create_merge_request

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

    context 'invalid branch name' do
      it 'is unprocessable' do
        post(
          :create_merge_request,
          params: {
            target_project_id: nil,
            branch_name: 'master',
            ref: 'master',
            namespace_id: project.namespace.to_param,
            project_id: project.to_param,
            id: issue.to_param
          },
          format: :json
        )

        expect(response.body).to eq('Branch already exists')
        expect(response).to have_gitlab_http_status(:unprocessable_entity)
      end
    end

    context 'target_project_id is set' do
      let(:target_project) { fork_project(project, user, repository: true) }
      let(:target_project_id) { target_project.id }

      it 'creates a new merge request', :sidekiq_might_not_need_inline do
        expect { create_merge_request }.to change(target_project.merge_requests, :count).by(1)
      end
    end

    def create_merge_request
      post(
        :create_merge_request,
        params: {
          namespace_id: project.namespace.to_param,
          project_id: project.to_param,
          id: issue.to_param,
          target_project_id: target_project_id
        },
        format: :json
      )
    end
  end

  describe 'POST #import_csv' do
    let_it_be(:project) { create(:project, :public) }

    let(:file) { fixture_file_upload('spec/fixtures/csv_comma.csv') }

    context 'unauthorized' do
      it 'returns 404 for guests' do
        sign_out(:user)

        import_csv

        expect(response).to have_gitlab_http_status :not_found
      end

      it 'returns 404 for project members with reporter role' do
        sign_in(user)
        project.add_reporter(user)

        import_csv

        expect(response).to have_gitlab_http_status :not_found
      end
    end

    context 'authorized' do
      before do
        sign_in(user)
        project.add_developer(user)
      end

      it "returns 302 for project members with developer role" do
        import_csv

        expect(flash[:notice]).to eq(_("Your issues are being imported. Once finished, you'll get a confirmation email."))
        expect(response).to redirect_to(project_issues_path(project))
      end

      it "shows error when upload fails" do
        expect_next_instance_of(UploadService) do |upload_service|
          expect(upload_service).to receive(:execute).and_return(nil)
        end

        import_csv

        expect(flash[:alert]).to include(_('File upload error.'))
        expect(response).to redirect_to(project_issues_path(project))
      end
    end

    def import_csv
      post :import_csv, params: { namespace_id: project.namespace.to_param,
                                  project_id: project.to_param,
                                  file: file }
    end
  end

  describe 'POST export_csv' do
    let(:viewer) { user }
    let(:issue) { create(:issue, project: project) }

    before do
      project.add_developer(user)
    end

    def request_csv
      post :export_csv, params: { namespace_id: project.namespace.to_param, project_id: project.to_param }
    end

    context 'when logged in' do
      before do
        sign_in(viewer)
      end

      it 'allows CSV export' do
        expect(IssuableExportCsvWorker).to receive(:perform_async).with(:issue, viewer.id, project.id, anything)

        request_csv

        expect(response).to redirect_to(project_issues_path(project))
        expect(controller).to set_flash[:notice].to match(/\AYour CSV export has started/i)
      end
    end

    context 'when not logged in' do
      let(:empty_project) { create(:project_empty_repo, :public) }

      it 'redirects to the sign in page' do
        request_csv

        expect(IssuableExportCsvWorker).not_to receive(:perform_async)
        expect(response).to redirect_to(new_user_session_path)
      end
    end
  end

  describe 'GET service_desk' do
    let_it_be(:project) { create(:project_empty_repo, :public) }
    let_it_be(:support_bot) { User.support_bot }
    let_it_be(:other_user) { create(:user) }
    let_it_be(:service_desk_issue_1) { create(:issue, project: project, author: support_bot) }
    let_it_be(:service_desk_issue_2) { create(:issue, project: project, author: support_bot, assignees: [other_user]) }
    let_it_be(:other_user_issue) { create(:issue, project: project, author: other_user) }

    def get_service_desk(extra_params = {})
      get :service_desk, params: extra_params.merge(namespace_id: project.namespace, project_id: project)
    end

    it 'adds an author filter for the support bot user' do
      get_service_desk

      expect(assigns(:issues)).to contain_exactly(service_desk_issue_1, service_desk_issue_2)
    end

    it 'does not allow any other author to be set' do
      get_service_desk(author_username: other_user.username)

      expect(assigns(:issues)).to contain_exactly(service_desk_issue_1, service_desk_issue_2)
    end

    it 'supports other filters' do
      get_service_desk(assignee_username: other_user.username)

      expect(assigns(:issues)).to contain_exactly(service_desk_issue_2)
    end

    it 'allows an assignee to be specified by id' do
      get_service_desk(assignee_id: other_user.id)

      expect(assigns(:users)).to contain_exactly(other_user, support_bot)
    end
  end

  describe 'GET #discussions' do
    let!(:discussion) { create(:discussion_note_on_issue, noteable: issue, project: issue.project) }

    context 'when authenticated' do
      before do
        project.add_developer(user)
        sign_in(user)
      end

      context do
        it_behaves_like 'discussions provider' do
          let!(:author) { create(:user) }
          let!(:project) { create(:project) }

          let!(:issue) { create(:issue, project: project, author: user) }

          let!(:note_on_issue1) { create(:discussion_note_on_issue, noteable: issue, project: issue.project, author: create(:user)) }
          let!(:note_on_issue2) { create(:discussion_note_on_issue, noteable: issue, project: issue.project, author: create(:user)) }

          let(:requested_iid) { issue.iid }
          let(:expected_discussion_count) { 3 }
          let(:expected_discussion_ids) do
            [
              issue.notes.first.discussion_id,
              note_on_issue1.discussion_id,
              note_on_issue2.discussion_id
            ]
          end
        end
      end

      it 'returns discussion json' do
        get :discussions, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }

        expect(json_response.first.keys).to match_array(%w[id reply_id expanded notes diff_discussion discussion_path individual_note resolvable resolved resolved_at resolved_by resolved_by_push commit_id for_commit project_id confidential])
      end

      it 'renders the author status html if there is a status' do
        create(:user_status, user: discussion.author)

        get :discussions, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }

        note_json = json_response.first['notes'].first

        expect(note_json['author']['status_tooltip_html']).to be_present
      end

      it 'does not cause an extra query for the status' do
        control = ActiveRecord::QueryRecorder.new do
          get :discussions, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }
        end

        create(:user_status, user: discussion.author)
        second_discussion = create(:discussion_note_on_issue, noteable: issue, project: issue.project, author: create(:user))
        create(:user_status, user: second_discussion.author)

        expect { get :discussions, params: { namespace_id: project.namespace, project_id: project, id: issue.iid } }
          .not_to exceed_query_limit(control)
      end

      context 'when user is setting notes filters' do
        let(:issuable) { issue }
        let(:issuable_parent) { project }
        let!(:discussion_note) { create(:discussion_note_on_issue, :system, noteable: issuable, project: project) }

        it_behaves_like 'issuable notes filter'
      end

      context 'with cross-reference system note', :request_store do
        let_it_be(:new_issue) { create(:issue) }

        let(:cross_reference) { "mentioned in #{new_issue.to_reference(issue.project)}" }

        before do
          create(:discussion_note_on_issue, :system, noteable: issue, project: issue.project, note: cross_reference)
        end

        it 'filters notes that the user should not see' do
          get :discussions, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }

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

        it 'does not result in N+1 queries' do
          # Instantiate the controller variables to ensure QueryRecorder has an accurate base count
          get :discussions, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }

          RequestStore.clear!

          control_count = ActiveRecord::QueryRecorder.new do
            get :discussions, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }
          end.count

          RequestStore.clear!

          create_list(:discussion_note_on_issue, 2, :system, noteable: issue, project: issue.project, note: cross_reference)

          expect { get :discussions, params: { namespace_id: project.namespace, project_id: project, id: issue.iid } }.not_to exceed_query_limit(control_count)
        end
      end

      context 'private project' do
        let!(:branch_note) { create(:discussion_note_on_issue, :system, noteable: issue, project: project) }
        let!(:commit_note) { create(:discussion_note_on_issue, :system, noteable: issue, project: project) }
        let!(:branch_note_meta) { create(:system_note_metadata, note: branch_note, action: "branch") }
        let!(:commit_note_meta) { create(:system_note_metadata, note: commit_note, action: "commit") }

        context 'user is allowed access' do
          before do
            project.add_user(user, :maintainer)
          end

          it 'displays all available notes' do
            get :discussions, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }

            expect(json_response.length).to eq(3)
          end
        end

        context 'user is a guest' do
          let(:json_response_note_ids) do
            json_response.collect { |discussion| discussion["notes"] }.flatten
              .collect { |note| note["id"].to_i }
          end

          before do
            project.add_guest(user)
          end

          it 'does not display notes w/type listed in TYPES_RESTRICTED_BY_ACCESS_LEVEL' do
            get :discussions, params: { namespace_id: project.namespace, project_id: project, id: issue.iid }

            expect(json_response.length).to eq(2)
            expect(json_response_note_ids).not_to include(branch_note.id)
          end
        end
      end
    end
  end

  describe 'GET #designs' do
    context 'when project has moved' do
      let(:new_project) { create(:project) }
      let(:issue) { create(:issue, project: new_project) }

      before do
        sign_in(user)

        project.route.destroy!
        new_project.redirect_routes.create!(path: project.full_path)
        new_project.add_developer(user)
      end

      it 'redirects from an old issue/designs correctly' do
        get :designs,
            params: {
              namespace_id: project.namespace,
              project_id: project,
              id: issue
            }

        expect(response).to redirect_to(designs_project_issue_path(new_project, issue))
        expect(response).to have_gitlab_http_status(:moved_permanently)
      end
    end
  end

  context 'private project with token authentication' do
    let_it_be(:private_project) { create(:project, :private) }

    it_behaves_like 'authenticates sessionless user', :index, :atom, ignore_incrementing: true do
      before do
        default_params.merge!(project_id: private_project, namespace_id: private_project.namespace)

        private_project.add_maintainer(user)
      end
    end

    it_behaves_like 'authenticates sessionless user', :calendar, :ics, ignore_incrementing: true do
      before do
        default_params.merge!(project_id: private_project, namespace_id: private_project.namespace)

        private_project.add_maintainer(user)
      end
    end
  end

  context 'public project with token authentication' do
    let_it_be(:public_project) { create(:project, :public) }

    it_behaves_like 'authenticates sessionless user', :index, :atom, public: true do
      before do
        default_params.merge!(project_id: public_project, namespace_id: public_project.namespace)
      end
    end

    it_behaves_like 'authenticates sessionless user', :calendar, :ics, public: true do
      before do
        default_params.merge!(project_id: public_project, namespace_id: public_project.namespace)
      end
    end
  end
end