-
Notifications
You must be signed in to change notification settings - Fork 189
/
test_updates.py
5796 lines (4937 loc) · 248 KB
/
test_updates.py
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
# Copyright 2011-2019 Red Hat, Inc. and others.
#
# This file is part of Bodhi.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""This module contains tests for bodhi.server.services.updates."""
from datetime import datetime, timedelta
from unittest import mock
from urllib import parse as urlparse
import copy
import re
import textwrap
import time
from fedora_messaging import api, testing as fml_testing
import koji
import requests
from webtest import TestApp
from bodhi.messages.schemas import update as update_schemas
from bodhi.server import main
from bodhi.server.config import config
from bodhi.server.models import (
Build, BuildrootOverride, Compose, Group, RpmPackage, ModulePackage, Release,
ReleaseState, RpmBuild, Update, UpdateRequest, UpdateStatus, UpdateType,
UpdateSeverity, UpdateSuggestion, User, TestGatingStatus)
from bodhi.server.util import call_api
from bodhi.tests.server.base import BaseTestCase
from bodhi.server.exceptions import BodhiException, LockedUpdateException
YEAR = time.localtime().tm_year
mock_valid_requirements = {
'target': 'bodhi.server.validators._get_valid_requirements',
'return_value': ['rpmlint', 'upgradepath'],
}
mock_uuid4_version1 = {
'target': 'uuid.uuid4',
'return_value': 'this is a consistent string',
}
mock_uuid4_version2 = {
'target': 'uuid.uuid4',
'return_value': 'this is another consistent string',
}
mock_taskotron_results = {
'target': 'bodhi.server.util.taskotron_results',
'return_value': [{
"outcome": "PASSED",
"data": {},
"testcase": {"name": "rpmlint"}
}],
}
mock_failed_taskotron_results = {
'target': 'bodhi.server.util.taskotron_results',
'return_value': [{
"outcome": "FAILED",
"data": {},
"testcase": {"name": "rpmlint"}
}],
}
mock_absent_taskotron_results = {
'target': 'bodhi.server.util.taskotron_results',
'return_value': [],
}
class TestNewUpdate(BaseTestCase):
"""
This class contains tests for the new_update() function.
"""
@mock.patch(**mock_valid_requirements)
def test_empty_build_name(self, *args):
res = self.app.post_json('/updates/', self.get_update(['']), status=400)
self.assertEqual(res.json_body['errors'][0]['name'], 'builds.0')
self.assertEqual(res.json_body['errors'][0]['description'], 'Required')
@mock.patch(**mock_valid_requirements)
def test_fail_on_edit_with_empty_build_list(self, *args):
update = self.get_update()
update['edited'] = update['builds'] # the update title..
update['builds'] = []
res = self.app.post_json('/updates/', update, status=400)
self.assertEqual(len(res.json_body['errors']), 2)
self.assertEqual(res.json_body['errors'][0]['name'], 'builds')
self.assertEqual(
res.json_body['errors'][0]['description'],
'You may not specify an empty list of builds.')
self.assertEqual(res.json_body['errors'][1]['name'], 'builds')
self.assertEqual(
res.json_body['errors'][1]['description'],
'ACL validation mechanism was unable to determine ACLs.')
@mock.patch(**mock_taskotron_results)
@mock.patch(**mock_valid_requirements)
def test_unicode_description(self, *args):
# We don't want the new update to obsolete the existing one.
self.db.delete(Update.query.one())
update = self.get_update('bodhi-2.0.0-2.fc17')
update['notes'] = 'This is wünderfül'
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
r = self.app.post_json('/updates/', update)
up = r.json_body
self.assertEqual(up['title'], 'bodhi-2.0.0-2.fc17')
self.assertEqual(up['notes'], 'This is wünderfül')
self.assertIsNotNone(up['date_submitted'])
@mock.patch(**mock_valid_requirements)
def test_duplicate_build(self, *args):
res = self.app.post_json(
'/updates/', self.get_update(['bodhi-2.0-2.fc17', 'bodhi-2.0-2.fc17']), status=400)
self.assertIn('Duplicate builds', res)
@mock.patch(**mock_valid_requirements)
def test_multiple_builds_of_same_package(self, *args):
res = self.app.post_json('/updates/', self.get_update(['bodhi-2.0-2.fc17',
'bodhi-2.0-3.fc17']),
status=400)
self.assertIn('Multiple bodhi builds specified', res)
@mock.patch(**mock_valid_requirements)
def test_invalid_autokarma(self, *args):
res = self.app.post_json('/updates/', self.get_update(stable_karma=-1),
status=400)
self.assertIn('-1 is less than minimum value 1', res)
res = self.app.post_json('/updates/', self.get_update(unstable_karma=1),
status=400)
self.assertIn('1 is greater than maximum value -1', res)
@mock.patch(**mock_valid_requirements)
def test_duplicate_update(self, *args):
res = self.app.post_json('/updates/', self.get_update('bodhi-2.0-1.fc17'),
status=400)
self.assertIn('Update for bodhi-2.0-1.fc17 already exists', res)
@mock.patch(**mock_valid_requirements)
def test_invalid_requirements(self, *args):
update = self.get_update()
update['requirements'] = 'rpmlint silly-dilly'
res = self.app.post_json('/updates/', update, status=400)
self.assertIn("Required check doesn't exist", res)
@mock.patch(**mock_valid_requirements)
def test_no_privs(self, *args):
user = User(name='bodhi')
self.db.add(user)
self.db.commit()
with mock.patch('bodhi.server.Session.remove'):
app = TestApp(main({}, testing='bodhi', session=self.db, **self.app_settings))
update_json = self.get_update('bodhi-2.1-1.fc17')
update_json['csrf_token'] = self.get_csrf_token(app)
with fml_testing.mock_sends():
res = app.post_json('/updates/', update_json, status=400)
expected_error = {
"location": "body",
"name": "builds",
"description": ("bodhi is not a member of \"packager\", which is a"
" mandatory packager group")
}
self.assertIn(expected_error, res.json_body['errors'])
@mock.patch(**mock_taskotron_results)
@mock.patch(**mock_valid_requirements)
def test_provenpackager_privs(self, *args):
"Ensure provenpackagers can push updates for any package"
user = User(name='bodhi')
self.db.add(user)
self.db.commit()
group = self.db.query(Group).filter_by(name='provenpackager').one()
user.groups.append(group)
with mock.patch('bodhi.server.Session.remove'):
app = TestApp(main({}, testing='bodhi', session=self.db, **self.app_settings))
update = self.get_update('bodhi-2.1-1.fc17')
update['csrf_token'] = app.get('/csrf').json_body['csrf_token']
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
res = app.post_json('/updates/', update)
self.assertNotIn('bodhi does not have commit access to bodhi', res)
build = self.db.query(RpmBuild).filter_by(nvr='bodhi-2.1-1.fc17').one()
self.assertIsNotNone(build.update)
@mock.patch(**mock_valid_requirements)
def test_invalid_acl_system(self, *args):
with mock.patch.dict(config, {'acl_system': 'null'}):
res = self.app.post_json('/updates/', self.get_update('bodhi-2.0-2.fc17'),
status=403)
self.assertIn("guest does not have commit access to bodhi", res)
def test_put_json_update(self):
self.app.put_json('/updates/', self.get_update(), status=405)
@mock.patch.dict('bodhi.server.validators.config', {'acl_system': 'dummy'})
@mock.patch(**mock_valid_requirements)
def test_post_json_update(self, *args):
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
self.app.post_json('/updates/', self.get_update('bodhi-2.0.0-1.fc17'))
@mock.patch.dict('bodhi.server.validators.config', {'acl_system': 'dummy'})
@mock.patch(**mock_uuid4_version1)
@mock.patch(**mock_valid_requirements)
def test_new_rpm_update(self, *args):
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
r = self.app.post_json('/updates/', self.get_update('bodhi-2.0.0-2.fc17'))
up = r.json_body
self.assertEqual(up['title'], 'bodhi-2.0.0-2.fc17')
self.assertEqual(up['status'], 'pending')
self.assertEqual(up['request'], 'testing')
self.assertEqual(up['user']['name'], 'guest')
self.assertEqual(up['release']['name'], 'F17')
self.assertEqual(up['type'], 'bugfix')
self.assertEqual(up['content_type'], 'rpm')
self.assertEqual(up['severity'], 'unspecified')
self.assertEqual(up['suggest'], 'unspecified')
self.assertEqual(up['close_bugs'], True)
# The notes are inheriting notes from the update that this update obsoleted.
self.assertEqual(up['notes'], 'this is a test update\n\n----\n\nUseful details!')
self.assertIsNotNone(up['date_submitted'])
self.assertEqual(up['date_modified'], None)
self.assertEqual(up['date_approved'], None)
self.assertEqual(up['date_pushed'], None)
self.assertEqual(up['locked'], False)
self.assertEqual(up['alias'], 'FEDORA-%s-033713b73b' % YEAR)
self.assertEqual(up['karma'], 0)
self.assertEqual(up['requirements'], 'rpmlint')
@mock.patch.dict('bodhi.server.validators.config', {'acl_system': 'dummy'})
@mock.patch(**mock_uuid4_version1)
@mock.patch(**mock_valid_requirements)
def test_new_rpm_update_unknown_build(self, *args):
with mock.patch('bodhi.server.buildsys.DevBuildsys.getBuild',
return_value=None):
r = self.app.post_json('/updates/', self.get_update('bodhi-2.0.0-2.fc17'),
status=400)
up = r.json_body
self.assertEqual(up['status'], 'error')
self.assertEqual(up['errors'][0]['description'],
"Build does not exist: bodhi-2.0.0-2.fc17")
@mock.patch.dict('bodhi.server.validators.config', {'acl_system': 'dummy'})
@mock.patch(**mock_uuid4_version1)
@mock.patch(**mock_valid_requirements)
def test_new_rpm_update_koji_error(self, *args):
with mock.patch('bodhi.server.buildsys.DevBuildsys.getBuild',
side_effect=koji.GenericError()):
r = self.app.post_json('/updates/', self.get_update('bodhi-2.0.0-2.fc17'),
status=400)
up = r.json_body
self.assertEqual(up['status'], 'error')
self.assertEqual(up['errors'][0]['description'],
"Koji error getting build: bodhi-2.0.0-2.fc17")
@mock.patch(**mock_valid_requirements)
def test_koji_config_url(self, *args):
"""
Test html rendering of default build link
"""
self.app.app.registry.settings['koji_web_url'] = 'https://koji.fedoraproject.org/koji/'
nvr = 'bodhi-2.0.0-2.fc17'
resp = self.app.post_json('/updates/', self.get_update(nvr))
resp = self.app.get(f"/updates/{resp.json['alias']}", headers={'Accept': 'text/html'})
self.assertRegex(str(resp), ('https://koji.fedoraproject.org/koji'
r'/search\?terms=.*\&type=build\&match=glob'))
@mock.patch(**mock_valid_requirements)
def test_koji_config_url_without_trailing_slash(self, *args):
"""
Test html rendering of default build link without trailing slash
"""
self.app.app.registry.settings['koji_web_url'] = 'https://koji.fedoraproject.org/koji'
nvr = 'bodhi-2.0.0-2.fc17'
resp = self.app.post_json('/updates/', self.get_update(nvr))
resp = self.app.get(f"/updates/{resp.json['alias']}", headers={'Accept': 'text/html'})
self.assertRegex(str(resp), ('https://koji.fedoraproject.org/koji'
r'/search\?terms=.*\&type=build\&match=glob'))
@mock.patch(**mock_valid_requirements)
def test_koji_config_mock_url_without_trailing_slash(self, *args):
"""
Test html rendering of build link using a mock config variable 'koji_web_url'
without a trailing slash in it
"""
self.app.app.registry.settings['koji_web_url'] = 'https://host.org'
nvr = 'bodhi-2.0.0-2.fc17'
resp = self.app.post_json('/updates/', self.get_update(nvr))
resp = self.app.get(f"/updates/{resp.json['alias']}", headers={'Accept': 'text/html'})
self.assertRegex(str(resp), ('https://host.org'
r'/search\?terms=.*\&type=build\&match=glob'))
@mock.patch.dict('bodhi.server.validators.config', {'acl_system': 'dummy'})
@mock.patch(**mock_uuid4_version1)
@mock.patch(**mock_valid_requirements)
def test_new_module_update(self, *args):
# Ensure there are no module packages in the DB to begin with.
self.assertEqual(self.db.query(ModulePackage).count(), 0)
self.create_release('27M')
# Then, create an update for one.
data = self.get_update('nginx-master-20170523')
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
r = self.app.post_json('/updates/', data)
up = r.json_body
self.assertEqual(up['title'], 'nginx-master-20170523')
self.assertEqual(up['status'], 'pending')
self.assertEqual(up['request'], 'testing')
self.assertEqual(up['user']['name'], 'guest')
self.assertEqual(up['release']['name'], 'F27M')
self.assertEqual(up['type'], 'bugfix')
self.assertEqual(up['content_type'], 'module')
self.assertEqual(up['severity'], 'unspecified')
self.assertEqual(up['suggest'], 'unspecified')
self.assertEqual(up['close_bugs'], True)
self.assertEqual(up['notes'], 'this is a test update')
self.assertIsNotNone(up['date_submitted'])
self.assertEqual(up['date_modified'], None)
self.assertEqual(up['date_approved'], None)
self.assertEqual(up['date_pushed'], None)
self.assertEqual(up['locked'], False)
self.assertEqual(up['alias'], 'FEDORA-%s-033713b73b' % YEAR)
self.assertEqual(up['karma'], 0)
self.assertEqual(up['requirements'], 'rpmlint')
# At the end, ensure that the right kind of package was created.
self.assertEqual(self.db.query(ModulePackage).count(), 1)
@mock.patch(**mock_valid_requirements)
def test_multiple_builds_of_same_module_stream(self, *args):
self.create_release('27M')
res = self.app.post_json('/updates/', self.get_update(['nodejs-6-20170101',
'nodejs-6-20170202']),
status=400)
self.assertIn('Multiple nodejs:6 builds specified', res)
@mock.patch(**mock_valid_requirements)
def test_multiple_builds_of_different_module_stream(self, *args):
self.create_release('27M')
with fml_testing.mock_sends(api.Message):
res = self.app.post_json('/updates/', self.get_update(['nodejs-6-20170101',
'nodejs-8-20170202']))
res = res.json
self.assertEqual(res['request'], 'testing')
self.assertEqual(len(res['builds']), 2)
self.assertEqual(res['builds'][0]['type'], 'module')
self.assertEqual(res['builds'][1]['type'], 'module')
self.assertEqual(res['builds'][0]['nvr'], 'nodejs-6-20170101')
self.assertEqual(res['builds'][1]['nvr'], 'nodejs-8-20170202')
self.assertEqual(res['title'], 'nodejs-6-20170101 nodejs-8-20170202')
# At the end, ensure that the right kind of packages were created.
self.assertEqual(self.db.query(ModulePackage).count(), 2)
@mock.patch(**mock_valid_requirements)
def test_multiple_updates_single_module_steam(self, *args):
# Ensure there are no module packages in the DB to begin with.
self.assertEqual(self.db.query(ModulePackage).count(), 0)
self.create_release('27M')
# First create an update for nodejs:6
with fml_testing.mock_sends(api.Message):
self.app.post_json('/updates/', self.get_update('nodejs-6-20170101'))
# Next create a second update for nodejs:6
with fml_testing.mock_sends(api.Message):
self.app.post_json('/updates/', self.get_update('nodejs-6-20170202'))
# At the end, ensure that the right kind of package was created.
self.assertEqual(self.db.query(ModulePackage).count(), 1)
pkg = self.db.query(ModulePackage).one()
self.assertEqual(pkg.name, 'nodejs:6')
# Assert that one update obsoleted the other
updates = self.db.query(Update).all()
self.assertEqual(updates[1].title, 'nodejs-6-20170101')
self.assertEqual(updates[1].status.name, 'obsolete')
self.assertIsNone(updates[1].request)
self.assertEqual(updates[2].title, 'nodejs-6-20170202')
self.assertEqual(updates[2].status.name, 'pending')
self.assertEqual(updates[2].request.name, 'testing')
@mock.patch(**mock_uuid4_version1)
@mock.patch(**mock_valid_requirements)
def test_new_container_update(self, *args):
self.create_release('28C')
data = self.get_update('mariadb-10.1-10.f28container')
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
r = self.app.post_json('/updates/', data, status=200)
up = r.json_body
self.assertEqual(up['title'], 'mariadb-10.1-10.f28container')
self.assertEqual(up['status'], 'pending')
self.assertEqual(up['request'], 'testing')
self.assertEqual(up['user']['name'], 'guest')
self.assertEqual(up['release']['name'], 'F28C')
self.assertEqual(up['type'], 'bugfix')
self.assertEqual(up['content_type'], 'container')
self.assertEqual(up['severity'], 'unspecified')
self.assertEqual(up['suggest'], 'unspecified')
self.assertEqual(up['close_bugs'], True)
self.assertEqual(up['notes'], 'this is a test update')
self.assertIsNotNone(up['date_submitted'])
self.assertEqual(up['date_modified'], None)
self.assertEqual(up['date_approved'], None)
self.assertEqual(up['date_pushed'], None)
self.assertEqual(up['locked'], False)
self.assertEqual(up['alias'], 'FEDORA-%s-033713b73b' % YEAR)
self.assertEqual(up['karma'], 0)
self.assertEqual(up['requirements'], 'rpmlint')
@mock.patch(**mock_uuid4_version1)
@mock.patch(**mock_valid_requirements)
def test_new_flatpak_update(self, *args):
self.create_release('28F')
data = self.get_update('mariadb-10.1-10.f28flatpak')
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
r = self.app.post_json('/updates/', data, status=200)
up = r.json_body
self.assertEqual(up['title'], 'mariadb-10.1-10.f28flatpak')
self.assertEqual(up['status'], 'pending')
self.assertEqual(up['request'], 'testing')
self.assertEqual(up['user']['name'], 'guest')
self.assertEqual(up['release']['name'], 'F28F')
self.assertEqual(up['type'], 'bugfix')
self.assertEqual(up['content_type'], 'flatpak')
self.assertEqual(up['severity'], 'unspecified')
self.assertEqual(up['suggest'], 'unspecified')
self.assertEqual(up['close_bugs'], True)
self.assertEqual(up['notes'], 'this is a test update')
self.assertIsNotNone(up['date_submitted'])
self.assertEqual(up['date_modified'], None)
self.assertEqual(up['date_approved'], None)
self.assertEqual(up['date_pushed'], None)
self.assertEqual(up['locked'], False)
self.assertEqual(up['alias'], 'FEDORA-%s-033713b73b' % YEAR)
self.assertEqual(up['karma'], 0)
self.assertEqual(up['requirements'], 'rpmlint')
@mock.patch.dict('bodhi.server.validators.config', {'acl_system': 'dummy'})
@mock.patch(**mock_valid_requirements)
def test_new_update_with_multiple_bugs(self, *args):
update = self.get_update('bodhi-2.0.0-2.fc17')
update['bugs'] = ['1234', '5678']
r = self.app.post_json('/updates/', update)
up = r.json_body
# This Update inherits one bug from the Update it obsoleted.
self.assertEqual(len(up['bugs']), 3)
self.assertEqual(up['bugs'][0]['bug_id'], 1234)
self.assertEqual(up['bugs'][1]['bug_id'], 5678)
self.assertEqual(up['bugs'][2]['bug_id'], 12345)
@mock.patch.dict('bodhi.server.validators.config', {'acl_system': 'dummy'})
@mock.patch(**mock_valid_requirements)
def test_new_update_with_multiple_bugs_as_str(self, *args):
update = self.get_update('bodhi-2.0.0-2.fc17')
update['bugs'] = '1234, 5678'
r = self.app.post_json('/updates/', update)
up = r.json_body
# This Update inherits one bug from the Update it obsoleted.
self.assertEqual(len(up['bugs']), 3)
self.assertEqual(up['bugs'][0]['bug_id'], 1234)
self.assertEqual(up['bugs'][1]['bug_id'], 5678)
self.assertEqual(up['bugs'][2]['bug_id'], 12345)
@mock.patch.dict('bodhi.server.validators.config', {'acl_system': 'dummy'})
@mock.patch(**mock_valid_requirements)
def test_new_update_with_invalid_bugs_as_str(self, *args):
update = self.get_update('bodhi-2.0.0-2.fc17')
update['bugs'] = '1234, blargh'
r = self.app.post_json('/updates/', update, status=400)
up = r.json_body
self.assertEqual(up['status'], 'error')
self.assertEqual(up['errors'][0]['description'],
"Invalid bug ID specified: {}".format(['1234', 'blargh']))
@mock.patch.dict('bodhi.server.validators.config', {'acl_system': 'dummy'})
@mock.patch(**mock_valid_requirements)
def test_new_update_with_existing_build(self, *args):
"""Test submitting a new update with a build already in the database"""
package = RpmPackage.get('bodhi')
self.db.add(RpmBuild(nvr='bodhi-2.0.0-3.fc17', package=package))
self.db.commit()
args = self.get_update('bodhi-2.0.0-3.fc17')
with fml_testing.mock_sends(api.Message):
resp = self.app.post_json('/updates/', args)
self.assertEqual(resp.json['title'], 'bodhi-2.0.0-3.fc17')
@mock.patch.dict('bodhi.server.validators.config', {'acl_system': 'dummy'})
@mock.patch(**mock_valid_requirements)
def test_new_update_with_existing_package(self, *args):
"""Test submitting a new update with a package that is already in the database."""
package = RpmPackage(name='existing-package')
self.db.add(package)
self.db.commit()
args = self.get_update('existing-package-2.4.1-5.fc17')
with fml_testing.mock_sends(api.Message):
resp = self.app.post_json('/updates/', args)
self.assertEqual(resp.json['title'], 'existing-package-2.4.1-5.fc17')
package = self.db.query(RpmPackage).filter_by(name='existing-package').one()
self.assertEqual(package.name, 'existing-package')
@mock.patch.dict('bodhi.server.validators.config', {'acl_system': 'dummy'})
@mock.patch(**mock_valid_requirements)
def test_new_update_with_missing_package(self, *args):
"""Test submitting a new update with a package that is not already in the database."""
args = self.get_update('missing-package-2.4.1-5.fc17')
with fml_testing.mock_sends(api.Message):
resp = self.app.post_json('/updates/', args)
self.assertEqual(resp.json['title'], 'missing-package-2.4.1-5.fc17')
package = self.db.query(RpmPackage).filter_by(name='missing-package').one()
self.assertEqual(package.name, 'missing-package')
@mock.patch(**mock_valid_requirements)
def test_cascade_package_requirements_to_update(self, *args):
package = self.db.query(RpmPackage).filter_by(name='bodhi').one()
package.requirements = 'upgradepath rpmlint'
self.db.commit()
args = self.get_update('bodhi-2.0.0-3.fc17')
# Don't specify any requirements so that they cascade from the package
del args['requirements']
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
r = self.app.post_json('/updates/', args)
up = r.json_body
self.assertEqual(up['title'], 'bodhi-2.0.0-3.fc17')
self.assertTrue('upgradepath' in up['requirements'])
self.assertTrue('rpmlint' in up['requirements'])
@mock.patch(**mock_valid_requirements)
def test_push_untested_critpath_to_release(self, *args):
"""
Ensure that we cannot push an untested critpath update directly to
stable.
"""
args = self.get_update('kernel-3.11.5-300.fc17')
args['request'] = 'stable'
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
up = self.app.post_json('/updates/', args).json_body
self.assertTrue(up['critpath'])
self.assertEqual(up['request'], 'testing')
@mock.patch(**mock_valid_requirements)
def test_obsoletion(self, *args):
nvr = 'bodhi-2.0.0-2.fc17'
args = self.get_update(nvr)
with mock.patch(**mock_uuid4_version1):
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
self.app.post_json('/updates/', args)
up = self.db.query(Build).filter_by(nvr=nvr).one().update
up.status = UpdateStatus.testing
up.request = None
args = self.get_update('bodhi-2.0.0-3.fc17')
with mock.patch(**mock_uuid4_version2):
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
r = self.app.post_json('/updates/', args).json_body
self.assertEqual(r['request'], 'testing')
# Since we're obsoleting something owned by someone else.
self.assertEqual(r['caveats'][0]['description'],
'This update has obsoleted bodhi-2.0.0-2.fc17, '
'and has inherited its bugs and notes.')
# Check for the comment multiple ways
# Note that caveats above don't support markdown, but comments do.
expected_comment = (
'This update has obsoleted [bodhi-2.0.0-2.fc17]({}), '
'and has inherited its bugs and notes.')
expected_comment = expected_comment.format(
urlparse.urljoin(config['base_address'],
'/updates/FEDORA-{}-033713b73b'.format(datetime.now().year)))
self.assertEqual(r['comments'][-1]['text'], expected_comment)
up = self.db.query(Build).filter_by(nvr=nvr).one().update
self.assertEqual(up.status, UpdateStatus.obsolete)
expected_comment = 'This update has been obsoleted by [bodhi-2.0.0-3.fc17]({}).'
expected_comment = expected_comment.format(
urlparse.urljoin(config['base_address'],
'/updates/FEDORA-{}-53345602d5'.format(datetime.now().year)))
self.assertEqual(up.comments[-1].text, expected_comment)
@mock.patch(**mock_valid_requirements)
def test_create_new_nonsecurity_update_when_previous_security_one_exists(self, *args):
"""
Assert that when non-security update obsoletes previous security update, caveat is reported
and submitted update type is changed to security.
"""
nvr = 'bodhi-2.0.0-2.fc17'
args = self.get_update(nvr)
args["type"] = "security"
args["severity"] = "high"
with mock.patch(**mock_uuid4_version1):
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
self.app.post_json('/updates/', args)
up = self.db.query(Build).filter_by(nvr=nvr).one().update
up.status = UpdateStatus.testing
up.request = None
args = self.get_update('bodhi-2.0.0-3.fc17')
with mock.patch(**mock_uuid4_version2):
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
r = self.app.post_json('/updates/', args).json_body
# Since we're trying to obsolete security update with non security update.
self.assertEqual(r['caveats'][0]['description'],
'Adjusting type of this update to security,'
'since it obsoletes another security update')
self.assertEqual(r['request'], 'testing')
# Since we're obsoleting something owned by someone else.
self.assertEqual(r['caveats'][1]['description'],
'This update has obsoleted bodhi-2.0.0-2.fc17, '
'and has inherited its bugs and notes.')
# Check for the comment multiple ways
# Note that caveats above don't support markdown, but comments do.
expected_comment = (
'This update has obsoleted [bodhi-2.0.0-2.fc17]({}), '
'and has inherited its bugs and notes.')
expected_comment = expected_comment.format(
urlparse.urljoin(config['base_address'],
'/updates/FEDORA-{}-033713b73b'.format(datetime.now().year)))
self.assertEqual(r['comments'][-1]['text'], expected_comment)
up = self.db.query(Build).filter_by(nvr=nvr).one().update
self.assertEqual(up.status, UpdateStatus.obsolete)
expected_comment = 'This update has been obsoleted by [bodhi-2.0.0-3.fc17]({}).'
expected_comment = expected_comment.format(
urlparse.urljoin(config['base_address'],
'/updates/FEDORA-{}-53345602d5'.format(datetime.now().year)))
self.assertEqual(up.comments[-1].text, expected_comment)
# Assert that the type of the new update is security.
up = self.db.query(Build).filter_by(nvr='bodhi-2.0.0-3.fc17').one().update
self.assertEqual(up.type, UpdateType.security)
@mock.patch(**mock_valid_requirements)
def test_obsoletion_security_update(self, *args):
"""Assert that security update can obsolete previous security update."""
nvr = 'bodhi-2.0.0-2.fc17'
args = self.get_update(nvr)
args["type"] = "security"
args["severity"] = "high"
with mock.patch(**mock_uuid4_version1):
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
self.app.post_json('/updates/', args)
up = self.db.query(Build).filter_by(nvr=nvr).one().update
up.status = UpdateStatus.testing
up.request = None
args = self.get_update('bodhi-2.0.0-3.fc17')
args["type"] = "security"
args["severity"] = "high"
with mock.patch(**mock_uuid4_version2):
with fml_testing.mock_sends(update_schemas.UpdateRequestTestingV1):
r = self.app.post_json('/updates/', args).json_body
self.assertEqual(r['request'], 'testing')
# Since we're obsoleting something owned by someone else.
self.assertEqual(r['caveats'][0]['description'],
'This update has obsoleted bodhi-2.0.0-2.fc17, '
'and has inherited its bugs and notes.')
# Check for the comment multiple ways
# Note that caveats above don't support markdown, but comments do.
expected_comment = (
'This update has obsoleted [bodhi-2.0.0-2.fc17]({}), '
'and has inherited its bugs and notes.')
expected_comment = expected_comment.format(
urlparse.urljoin(config['base_address'],
'/updates/FEDORA-{}-033713b73b'.format(datetime.now().year)))
self.assertEqual(r['comments'][-1]['text'], expected_comment)
up = self.db.query(Build).filter_by(nvr=nvr).one().update
self.assertEqual(up.status, UpdateStatus.obsolete)
expected_comment = 'This update has been obsoleted by [bodhi-2.0.0-3.fc17]({}).'
expected_comment = expected_comment.format(
urlparse.urljoin(config['base_address'],
'/updates/FEDORA-{}-53345602d5'.format(datetime.now().year)))
self.assertEqual(up.comments[-1].text, expected_comment)
@mock.patch(**mock_valid_requirements)
@mock.patch('bodhi.server.services.updates.Update.new', side_effect=IOError('oops!'))
def test_unexpected_exception(self, *args):
"""Ensure that an unexpected Exception is handled by new_update()."""
update = self.get_update('bodhi-2.3.2-1.fc17')
r = self.app.post_json('/updates/', update, status=400)
self.assertEqual(r.json_body['status'], 'error')
self.assertEqual(r.json_body['errors'][0]['description'],
"Unable to create update. oops!")
# Despite the Exception, the RpmBuild should still exist in the database
build = self.db.query(RpmBuild).filter(RpmBuild.nvr == 'bodhi-2.3.2-1.fc17').one()
self.assertEqual(build.package.name, 'bodhi')
@mock.patch(**mock_valid_requirements)
@mock.patch('bodhi.server.services.updates.Update.obsolete_older_updates',
side_effect=RuntimeError("bet you didn't see this coming!"))
def test_obsoletion_with_exception(self, *args):
"""
Assert that an exception during obsoletion is properly handled.
"""
nvr = 'bodhi-2.0.0-2.fc17'
args = self.get_update(nvr)
with mock.patch(**mock_uuid4_version1):
with fml_testing.mock_sends(api.Message):
self.app.post_json('/updates/', args)
up = self.db.query(Build).filter_by(nvr=nvr).one().update
up.status = UpdateStatus.testing
up.request = None
args = self.get_update('bodhi-2.0.0-3.fc17')
with mock.patch(**mock_uuid4_version2):
with fml_testing.mock_sends(api.Message):
r = self.app.post_json('/updates/', args).json_body
self.assertEqual(r['request'], 'testing')
# The exception handler should have put an error message in the caveats.
self.assertEqual(r['caveats'][0]['description'],
"Problem obsoleting older updates: bet you didn't see this coming!")
# Check for the comment multiple ways. The comment will be about the update being submitted
# for testing instead of being about the obsoletion, since the obsoletion failed.
# Note that caveats above don't support markdown, but comments do.
expected_comment = 'This update has been submitted for testing by guest. '
expected_comment = expected_comment.format(
urlparse.urljoin(config['base_address'], '/updates/FEDORA-2016-033713b73b'))
self.assertEqual(r['comments'][-1]['text'], expected_comment)
up = self.db.query(Build).filter_by(nvr=nvr).one().update
# The old update failed to get obsoleted.
self.assertEqual(up.status, UpdateStatus.testing)
expected_comment = 'This update has been submitted for testing by guest. '
self.assertEqual(up.comments[-1].text, expected_comment)
@mock.patch(**mock_valid_requirements)
def test_security_update_without_severity(self, *args):
"""Ensure that severity is required for a security update."""
update = self.get_update('bodhi-2.3.2-1.fc17')
update['type'] = 'security'
update['severity'] = 'unspecified'
r = self.app.post_json('/updates/', update, status=400)
self.assertEqual(r.json_body['status'], 'error')
self.assertEqual(r.json_body['errors'][0]['description'],
"Must specify severity for a security update")
class TestSetRequest(BaseTestCase):
"""
This class contains tests for the set_request() function.
"""
@mock.patch(**mock_valid_requirements)
def test_set_request_locked_update(self, *args):
"""Ensure that we get an error if trying to set request of a locked update"""
nvr = 'bodhi-2.0-1.fc17'
up = self.db.query(Build).filter_by(nvr=nvr).one().update
up.locked = True
post_data = dict(update=nvr, request='stable',
csrf_token=self.app.get('/csrf').json_body['csrf_token'])
res = self.app.post_json(f'/updates/{up.alias}/request', post_data, status=400)
self.assertEqual(res.json_body['status'], 'error')
self.assertEqual(res.json_body['errors'][0]['description'],
"Can't change request on a locked update")
@mock.patch(**mock_valid_requirements)
def test_set_request_archived_release(self, *args):
"""Ensure that we get an error if trying to setrequest of a update in an archived release"""
nvr = 'bodhi-2.0-1.fc17'
up = self.db.query(Build).filter_by(nvr=nvr).one().update
up.locked = False
up.release.state = ReleaseState.archived
post_data = dict(update=up.alias, request='stable',
csrf_token=self.app.get('/csrf').json_body['csrf_token'])
res = self.app.post_json(f'/updates/{up.alias}/request', post_data, status=400)
self.assertEqual(res.json_body['status'], 'error')
self.assertEqual(res.json_body['errors'][0]['description'],
"Can't change request for an archived release")
@mock.patch('bodhi.server.services.updates.log.info')
@mock.patch.dict(config, {'test_gating.required': True})
def test_test_gating_status_failed(self, info):
"""If the update's test_gating_status is failed, a user should not be able to push."""
nvr = 'bodhi-2.0-1.fc17'
up = self.db.query(Build).filter_by(nvr=nvr).one().update
up.locked = False
up.requirements = ''
up.test_gating_status = TestGatingStatus.failed
up.date_testing = datetime.utcnow() - timedelta(days=8)
up.request = None
post_data = dict(update=nvr, request='stable', csrf_token=self.get_csrf_token())
res = self.app.post_json(f'/updates/{up.alias}/request', post_data, status=400)
up = self.db.query(Build).filter_by(nvr=nvr).one().update
self.assertEqual(up.request, None)
self.assertEqual(res.json_body['status'], 'error')
self.assertEqual(res.json_body['errors'][0]['description'],
"Requirement not met Required tests did not pass on this update")
info_logs = '\n'.join([c[1][0] for c in info.mock_calls])
self.assertTrue(
f'Unable to set request for {up.alias} to stable due to failed requirements: Required '
'tests did not pass on this update' in info_logs)
@mock.patch.dict(config, {'test_gating.required': True})
def test_test_gating_status_passed(self):
"""If the update's test_gating_status is passed, a user should be able to push."""
nvr = 'bodhi-2.0-1.fc17'
up = self.db.query(Build).filter_by(nvr=nvr).one().update
up.locked = False
up.requirements = ''
up.test_gating_status = TestGatingStatus.passed
up.date_testing = datetime.utcnow() - timedelta(days=8)
post_data = dict(update=nvr, request='stable', csrf_token=self.get_csrf_token())
with fml_testing.mock_sends(api.Message):
res = self.app.post_json(f'/updates/{up.alias}/request', post_data, status=200)
up = self.db.query(Build).filter_by(nvr=nvr).one().update
self.assertEqual(up.request, UpdateRequest.stable)
self.assertEqual(res.json['update']['request'], 'stable')
@mock.patch(**mock_valid_requirements)
@mock.patch('bodhi.server.services.updates.Update.set_request',
side_effect=BodhiException('BodhiException. oops!'))
@mock.patch('bodhi.server.services.updates.Update.check_requirements',
return_value=(True, "a fake reason"))
@mock.patch('bodhi.server.services.updates.log.error')
def test_BodhiException_exception(self, log_error, check_requirements, send_request, *args):
"""Ensure that an BodhiException Exception is handled by set_request()."""
nvr = 'bodhi-2.0-1.fc17'
up = self.db.query(Build).filter_by(nvr=nvr).one().update
up.locked = False
up.release.state = ReleaseState.current
post_data = dict(update=up.alias, request='stable',
csrf_token=self.app.get('/csrf').json_body['csrf_token'])
res = self.app.post_json(f"/updates/{post_data['update']}/request", post_data,
status=400)
self.assertEqual(res.json_body['status'], 'error')
self.assertEqual(res.json_body['errors'][0]['description'],
'BodhiException. oops!')
log_error.assert_called_once()
self.assertEqual("Failed to set the request: %s", log_error.call_args_list[0][0][0])
@mock.patch(**mock_valid_requirements)
@mock.patch('bodhi.server.services.updates.Update.set_request',
side_effect=IOError('IOError. oops!'))
@mock.patch('bodhi.server.services.updates.Update.check_requirements',
return_value=(True, "a fake reason"))
@mock.patch('bodhi.server.services.updates.log.exception')
def test_unexpected_exception(self, log_exception, check_requirements, send_request, *args):
"""Ensure that an unexpected Exception is handled by set_request()."""
nvr = 'bodhi-2.0-1.fc17'
up = self.db.query(Build).filter_by(nvr=nvr).one().update
up.locked = False
up.release.state = ReleaseState.current
post_data = dict(update=nvr, request='stable',
csrf_token=self.app.get('/csrf').json_body['csrf_token'])
res = self.app.post_json(f'/updates/{up.alias}/request', post_data, status=400)
self.assertEqual(res.json_body['status'], 'error')
self.assertEqual(res.json_body['errors'][0]['description'],
'IOError. oops!')
log_exception.assert_called_once_with("Unhandled exception in set_request")
class TestEditUpdateForm(BaseTestCase):
def test_edit_with_permission(self):
"""
Test a logged in User with permissions on the update can see the form
"""
resp = self.app.get(
'/updates/FEDORA-{}-a3bbe1a8f2/edit'.format(datetime.utcnow().year),
headers={'accept': 'text/html'})
self.assertIn('Editing an update requires JavaScript', resp)
# Make sure that unspecified comes first, as it should be the default.
regex = r''
for value in ('unspecified', 'reboot', 'logout'):
regex = regex + r'name="suggest" value="{}".*'.format(value)
self.assertTrue(re.search(regex, resp.body.decode('utf8').replace('\n', ' ')))
def test_edit_without_permission(self):
"""
Test a logged in User without permissions on the update can't see the form
"""
with mock.patch('bodhi.server.Session.remove'):
app = TestApp(main({}, testing='anonymous', session=self.db, **self.app_settings))
resp = app.get(
'/updates/FEDORA-{}-a3bbe1a8f2/edit'.format(datetime.utcnow().year), status=400,
headers={'accept': 'text/html'})
self.assertIn(
'anonymous is not a member of "packager", which is a mandatory packager group', resp)
def test_edit_not_loggedin(self):
"""
Test a non logged in User can't see the form
"""
anonymous_settings = copy.copy(self.app_settings)
anonymous_settings.update({
'authtkt.secret': 'whatever',
'authtkt.secure': True,
})
app = TestApp(main({}, session=self.db, **anonymous_settings))
resp = app.get('/updates/FEDORA-2017-a3bbe1a8f2/edit', status=403,
headers={'accept': 'text/html'})
self.assertIn('<h1>403 <small>Forbidden</small></h1>', resp)
self.assertIn('<p class="lead">Access was denied to this resource.</p>', resp)
def test_disabled_unspecified_severity_for_security_update(self):
alias = Build.query.filter_by(nvr='bodhi-2.0-1.fc17').one().update.alias
update_json = self.get_update()
update_json['csrf_token'] = self.app.get('/csrf').json_body['csrf_token']
update_json['edited'] = alias
update_json['requirements'] = ''
update_json['type'] = 'security'
update_json['severity'] = 'low'
with fml_testing.mock_sends(api.Message):
self.app.post_json('/updates/', update_json)
resp = self.app.get(f'/updates/{alias}/edit',
headers={'accept': 'text/html'})
self.assertRegex(str(resp), ('<input type="radio" name="severity" '
'value="unspecified"\\n.*disabled="disabled"\\n.*>'))
class TestUpdatesService(BaseTestCase):
def test_content_type(self):
"""Assert that the content type is displayed in the update template."""
alias = Update.query.one().alias
res = self.app.get(f'/updates/{alias}', status=200, headers={'Accept': 'text/html'})
self.assertTrue(
('<strong>Content Type</strong>\n </div>\n <div>\n'
' RPM') in res.text)
def test_content_type_none(self):