/
test_models.py
1918 lines (1634 loc) · 79.6 KB
/
test_models.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
# -*- coding: utf-8 -*-
# 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.
"""Test suite for bodhi.server.models"""
from datetime import datetime, timedelta
from HTMLParser import HTMLParser
import json
import time
import unittest
from pyramid.testing import DummyRequest
from sqlalchemy.exc import IntegrityError
import cornice
import mock
from bodhi.server import models as model, buildsys, mail, util, Session
from bodhi.server.config import config
from bodhi.server.exceptions import BodhiException
from bodhi.server.models import (
BugKarma, ReleaseState, UpdateRequest, UpdateSeverity, UpdateStatus,
UpdateSuggestion, UpdateType, TestGatingStatus)
from bodhi.tests.server.base import BaseTestCase
class DummyUser(object):
name = 'guest'
class ModelTest(BaseTestCase):
"""Base unit test case for the models."""
klass = None
attrs = {}
_populate_db = False
def setUp(self):
super(ModelTest, self).setUp()
buildsys.setup_buildsystem({'buildsystem': 'dev'})
if type(self) != ModelTest:
try:
new_attrs = {}
new_attrs.update(self.attrs)
new_attrs.update(self.do_get_dependencies())
self.obj = self.klass(**new_attrs)
self.db.add(self.obj)
self.db.flush()
return self.obj
except:
self.db.rollback()
raise
def do_get_dependencies(self):
""" Use this method to pull in other objects that need to be
created for this object to be built properly.
"""
return {}
def test_create_obj(self):
pass
def test_query_obj(self):
for key, value in self.attrs.iteritems():
self.assertEqual(getattr(self.obj, key), value)
def test_json(self):
""" Ensure our models can return valid JSON """
if type(self) != ModelTest:
assert json.dumps(self.obj.__json__())
def test_get(self):
if type(self) != ModelTest:
for col in self.obj.__get_by__:
self.assertEqual(self.klass.get(getattr(self.obj, col), self.db), self.obj)
class TestQueryProperty(BaseTestCase):
def test_session(self):
"""Assert the session the query property uses is from the scoped session."""
query = model.Package.query
self.assertTrue(self.db is query.session)
class TestPolymorphicDiscovery(BaseTestCase):
def test_find_child_for_rpm(self):
subclass = model.Package.find_polymorphic_child(model.ContentType.rpm)
self.assertEqual(subclass, model.RpmPackage)
subclass = model.Build.find_polymorphic_child(model.ContentType.rpm)
self.assertEqual(subclass, model.RpmBuild)
subclass = model.Package.find_polymorphic_child(model.ContentType.module)
self.assertEqual(subclass, model.ModulePackage)
subclass = model.Build.find_polymorphic_child(model.ContentType.module)
self.assertEqual(subclass, model.ModuleBuild)
def test_find_child_with_bad_identity(self):
with self.assertRaises(NameError):
model.Package.find_polymorphic_child(model.UpdateType.security)
def test_find_child_with_bad_base_class(self):
with self.assertRaises(KeyError):
model.Update.find_polymorphic_child(model.ContentType.rpm)
def test_find_child_with_badly_typed_argument(self):
with self.assertRaises(TypeError):
model.Update.find_polymorphic_child("whatever")
class TestComment(BaseTestCase):
def test_text_not_nullable(self):
"""Assert that the text column does not allow NULL values.
For history about why this is important, see
https://github.com/fedora-infra/bodhi/issues/949.
"""
self.assertEqual(model.Comment.__table__.columns['text'].nullable, False)
def test_get_unigue_testcase_feedback(self):
update = self.create_update(
(u'bodhi-2.3.3-1.fc24', u'python-fedora-atomic-composer-2016.3-1.fc24'))
package = update.builds[0].package
test1 = model.TestCase(name=u"Test 1", package=package)
test2 = model.TestCase(name=u"Test 2", package=package)
test3 = model.TestCase(name=u"Test 2", package=package)
testcase_feedback = [{'testcase': test1, 'karma': 1},
{'testcase': test2, 'karma': 1},
{'testcase': test3, 'karma': 1}]
update.comment(session=self.db, text=u"test", karma=1, author=u"test",
testcase_feedback=testcase_feedback)
comments = update.comments
feedback = comments[0].unique_testcase_feedback
feedback_titles = [f.testcase.name for f in feedback]
feedback_titles_expected = [u"Test 1", u"Test 2"]
feedback_karma_sum = sum([f.karma for f in feedback])
self.assertEqual(len(feedback), 2)
self.assertEqual(sorted(feedback_titles), sorted(feedback_titles_expected))
self.assertEqual(feedback_karma_sum, 2)
class TestRelease(ModelTest):
"""Unit test case for the ``Release`` model."""
klass = model.Release
attrs = dict(
name=u"F11",
long_name=u"Fedora 11",
id_prefix=u"FEDORA",
version=u'11',
branch=u'f11',
dist_tag=u"dist-f11",
stable_tag=u"dist-f11-updates",
testing_tag=u"dist-f11-updates-testing",
candidate_tag=u"dist-f11-updates-candidate",
pending_signing_tag=u"dist-f11-updates-testing-signing",
pending_testing_tag=u"dist-f11-updates-testing-pending",
pending_stable_tag=u"dist-f11-updates-pending",
override_tag=u"dist-f11-override",
state=model.ReleaseState.current)
def test_version_int(self):
self.assertEqual(self.obj.version_int, 11)
def test_all_releases(self):
releases = model.Release.all_releases(self.db)
state = ReleaseState.from_string(releases.keys()[0])
assert 'long_name' in releases[state.value][0], releases
# Make sure it's the same cached object
assert releases is model.Release.all_releases(self.db)
class MockWiki(object):
""" Mocked simplemediawiki.MediaWiki class. """
def __init__(self, response):
self.response = response
self.query = None
def __call__(self, *args, **kwargs):
return self
def call(self, query):
self.query = query
return self.response
class TestPackageUniqueConstraints(BaseTestCase):
"""Tests for the Package model's uniqueness constraints."""
def test_two_package_different_types(self):
"""Assert two different package types with the same name is fine."""
package1 = model.Package(name=u'python-requests')
package2 = model.RpmPackage(name=u'python-requests')
self.db.add(package1)
self.db.add(package2)
self.db.flush()
def test_two_package_same_type(self):
"""Assert two packages of the same type with the same name is *not* fine."""
package1 = model.RpmPackage(name=u'python-requests')
package2 = model.RpmPackage(name=u'python-requests')
self.db.add(package1)
self.db.add(package2)
self.assertRaises(IntegrityError, self.db.flush)
class TestModulePackage(ModelTest, unittest.TestCase):
"""Unit test case for the ``ModulePackage`` model."""
klass = model.ModulePackage
attrs = dict(name=u"TurboGears")
def do_get_dependencies(self):
return dict(
committers=[model.User(name=u'lmacken')]
)
def setUp(self):
super(TestModulePackage, self).setUp()
self.package = model.ModulePackage(name=u'the-greatest-package')
self.db.add(self.package)
def test_adding_rpmbuild(self):
"""Assert that validation fails when adding a RpmBuild."""
build1 = model.ModuleBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
build2 = model.RpmBuild(nvr=u'the-greatest-package-1.1.0-fc17.1')
self.package.builds.append(build1)
with self.assertRaises(ValueError) as exc_context:
self.package.builds.append(build2)
self.assertEqual(
unicode(exc_context.exception),
("A RPM Build cannot be associated with a Module Package. A Package's "
"builds must be the same type as the package."))
def test_adding_list_of_module_and_rpmbuild(self):
"""Assert that validation fails when adding a ModuleBuild and RpmBuild via a list."""
build1 = model.ModuleBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
build2 = model.RpmBuild(nvr=u'the-greatest-package-1.1.0-fc17.1')
with self.assertRaises(ValueError) as exc_context:
self.package.builds = [build1, build2]
self.assertEqual(
unicode(exc_context.exception),
("A RPM Build cannot be associated with a Module Package. A Package's "
"builds must be the same type as the package."))
def test_backref_no_builds(self):
"""Assert that a ModuleBuild can be appended via a backref."""
build = model.ModuleBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
build.package = self.package
# This should not raise any Exception.
self.db.flush()
def test_backref_rpmbuild(self):
"""Assert that adding an RpmBuild via backref fails validation."""
build1 = model.ModuleBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
build2 = model.RpmBuild(nvr=u'the-greatest-package-1.1.0-fc17.1')
build1.package = self.package
with self.assertRaises(ValueError) as exc_context:
build2.package = self.package
self.assertEqual(
unicode(exc_context.exception),
("A RPM Build cannot be associated with a Module Package. A Package's "
"builds must be the same type as the package."))
def test_backref_second_modulebuild(self):
"""Assert that two ModuleBuilds can be appended via backrefs."""
build1 = model.ModuleBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
build2 = model.ModuleBuild(nvr=u'the-greatest-package-1.1.0-fc17.1')
build1.package = self.package
build2.package = self.package
# This should not raise any Exception.
self.db.flush()
def test_no_builds(self):
"""Assert that one ModuleBuild can be appended."""
build = model.ModuleBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
self.package.builds.append(build)
# This should not raise any Exception.
self.db.flush()
def test_same_build_types(self):
"""Assert that two builds of the module type can be added and that validation passes."""
build1 = model.ModuleBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
build2 = model.ModuleBuild(nvr=u'the-greatest-package-1.1.0-fc17.1')
self.package.builds += [build1, build2]
# This should not raise any Exception.
self.db.flush()
class TestRpmPackage(ModelTest, unittest.TestCase):
"""Unit test case for the ``Package`` model."""
klass = model.RpmPackage
attrs = dict(name=u"TurboGears")
def setUp(self):
super(TestRpmPackage, self).setUp()
self.package = model.RpmPackage(name=u'the-greatest-package')
self.db.add(self.package)
def do_get_dependencies(self):
return dict(
committers=[model.User(name=u'lmacken')]
)
def test_wiki_test_cases(self):
"""Test querying the wiki for test cases"""
# Mock out mediawiki so we don't do network calls in our tests
response = {
'query': {
'categorymembers': [{
'title': u'Fake test case',
}],
}
}
# Now, our actual test.
with mock.patch('bodhi.server.models.MediaWiki', MockWiki(response)):
config['query_wiki_test_cases'] = True
pkg = model.RpmPackage(name=u'gnome-shell')
pkg.fetch_test_cases(self.db)
assert pkg.test_cases
def test_adding_modulebuild(self):
"""Assert that validation fails when adding a ModuleBuild."""
build1 = model.RpmBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
build2 = model.ModuleBuild(nvr=u'the-greatest-package-1.1.0-fc17.1')
self.package.builds.append(build1)
with self.assertRaises(ValueError) as exc_context:
self.package.builds.append(build2)
self.assertEqual(
unicode(exc_context.exception),
("A Module Build cannot be associated with a RPM Package. A Package's "
"builds must be the same type as the package."))
def test_backref_no_builds(self):
"""Assert that a RpmBuild can be appended via a backref."""
build = model.RpmBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
build.package = self.package
# This should not raise any Exception.
self.db.flush()
def test_backref_modulebuild(self):
"""Assert that adding a ModuleBuild via backref fails validation."""
build1 = model.RpmBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
build2 = model.ModuleBuild(nvr=u'the-greatest-package-1.1.0-fc17.1')
build1.package = self.package
with self.assertRaises(ValueError) as exc_context:
build2.package = self.package
self.assertEqual(
unicode(exc_context.exception),
("A Module Build cannot be associated with a RPM Package. A Package's "
"builds must be the same type as the package."))
def test_backref_second_modulebuild(self):
"""Assert that two RpmBuilds can be appended via backrefs."""
build1 = model.RpmBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
build2 = model.RpmBuild(nvr=u'the-greatest-package-1.1.0-fc17.1')
build1.package = self.package
build2.package = self.package
# This should not raise any Exception.
self.db.flush()
def test_committers(self):
assert self.obj.committers[0].name == u'lmacken'
def test_no_builds(self):
"""Assert that one RpmBuild can be appended."""
build = model.RpmBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
self.package.builds.append(build)
# This should not raise any Exception.
self.db.flush()
def test_same_build_types(self):
"""Assert that two builds of the RPM type can be added and that validation passes."""
build1 = model.RpmBuild(nvr=u'the-greatest-package-1.0.0-fc17.1')
build2 = model.RpmBuild(nvr=u'the-greatest-package-1.1.0-fc17.1')
self.package.builds += [build1, build2]
# This should not raise any Exception.
self.db.flush()
@mock.patch('bodhi.server.util.requests.get')
def test_get_pkg_committers_from_pagure(self, mock_get):
""" Ensure that the package committers can be found using the Pagure
API.
"""
json_output = {
"access_groups": {
"admin": [],
"commit": ['factory2'],
"ticket": []
},
"access_users": {
"admin": [],
"commit": [],
"owner": [
"mprahl"
],
"ticket": ["jsmith"]
},
"close_status": [],
"custom_keys": [],
"date_created": "1494947106",
"description": "Python",
"fullname": "rpms/python",
"id": 2,
"milestones": {},
"name": "python",
"namespace": "rpms",
"parent": None,
"priorities": {},
"tags": [],
"user": {
"fullname": "Matt Prahl",
"name": "mprahl"
}
}
mock_get.return_value.json.return_value = json_output
mock_get.return_value.status_code = 200
rv = self.package.get_pkg_committers_from_pagure()
assert rv == (['mprahl'], ['factory2']), rv
@mock.patch('bodhi.server.util.requests.get')
def test_get_pkg_committers_container_from_pagure(self, mock_get):
""" Ensure that the container committers can be found using the Pagure
API.
"""
json_output = {
"access_groups": {
"admin": ["factory2"],
"commit": [],
"ticket": []
},
"access_users": {
"admin": [],
"commit": ["tbrady"],
"owner": ["mprahl"],
"ticket": ["jsmith"]
},
"close_status": [],
"custom_keys": [],
"date_created": "1494947106",
"description": "Python",
"fullname": "container/python",
"id": 2,
"milestones": {},
"name": "python",
"namespace": "container",
"parent": None,
"priorities": {},
"tags": [],
"user": {
"fullname": "Matt Prahl",
"name": "mprahl"
}
}
mock_get.return_value.json.return_value = json_output
mock_get.return_value.status_code = 200
# Even though Bodhi doesn't support containers yet, let's mock this
# package to have the type set to `container` to make sure the code in
# get_pkg_committers_from_pagure works with containers in the future.
self.package.type = mock.Mock()
self.package.type.name = 'container'
rv = self.package.get_pkg_committers_from_pagure()
assert rv == (['tbrady', 'mprahl'], ['factory2']), rv
class TestBuild(ModelTest):
"""Test class for the ``Build`` model."""
klass = model.Build
attrs = dict(nvr=u"TurboGears-1.0.8-3.fc11")
class TestRpmBuild(ModelTest):
"""Unit test case for the ``RpmBuild`` model."""
klass = model.RpmBuild
attrs = dict(nvr=u"TurboGears-1.0.8-3.fc11")
def do_get_dependencies(self):
return dict(release=model.Release(**TestRelease.attrs),
package=model.RpmPackage(**TestRpmPackage.attrs))
def test_release_relation(self):
self.assertEqual(self.obj.release.name, u"F11")
self.assertEqual(len(self.obj.release.builds), 1)
self.assertEqual(self.obj.release.builds[0], self.obj)
def test_package_relation(self):
self.assertEqual(self.obj.package.name, u"TurboGears")
self.assertEqual(len(self.obj.package.builds), 1)
self.assertEqual(self.obj.package.builds[0], self.obj)
def test_epoch(self):
self.obj.epoch = '1'
self.assertEqual(self.obj.evr, ("1", "1.0.8", "3.fc11"))
def test_url(self):
self.assertEqual(self.obj.get_url(), u'/TurboGears-1.0.8-3.fc11')
class TestUpdateValidateBuilds(BaseTestCase):
"""Tests for the :class:`Update` validator for builds."""
def setUp(self):
super(TestUpdateValidateBuilds, self).setUp()
self.package = model.RpmPackage(name='the-greatest-package')
self.update = model.Update(
title='The best update of all time.',
user=model.User.query.filter_by(name=u'guest').one(),
request=model.UpdateRequest.testing,
notes=u'Useless details!',
release=model.Release.query.filter_by(name=u'F17').one(),
date_submitted=datetime(1984, 11, 2),
requirements=u'rpmlint',
stable_karma=3,
unstable_karma=-3,
type=UpdateType.bugfix
)
def test_no_builds(self):
"""Assert when the first build is appended, the validator passes."""
build = model.Build(
nvr='the-greatest-package-1.0.0-fc17.1',
package_id=self.package.id,
release_id=self.update.release.id,
)
self.update.builds.append(build)
def test_same_build_types(self):
"""Assert when all builds are the same type, validation passes."""
build1 = model.RpmBuild(
nvr='the-greatest-package-1.0.0-fc17.1',
package_id=self.package.id,
release_id=self.update.release.id,
)
build2 = model.RpmBuild(
nvr='the-greatest-package-1.1.0-fc17.1',
package_id=self.package.id,
release_id=self.update.release.id,
)
self.update.builds += [build1, build2]
def test_different_build_types(self):
"""Assert when all builds are a different type, validation fails."""
build1 = model.Build(
nvr='the-greatest-package-1.0.0-fc17.1',
package_id=self.package.id,
release_id=self.update.release.id,
)
build2 = model.RpmBuild(
nvr='the-greatest-package-1.1.0-fc17.1',
package_id=self.package.id,
release_id=self.update.release.id,
)
self.update.builds.append(build1)
self.assertRaises(ValueError, self.update.builds.append, build2)
def test_backref_no_builds(self):
"""Assert when the first build is appended via a backref, the validator passes."""
build = model.Build(
nvr='the-greatest-package-1.0.0-fc17.1',
package_id=self.package.id,
release_id=self.update.release.id,
)
build.update = self.update
def test_backref_same_build_types(self):
"""Assert when all builds are the same type and set via backref validation passes."""
build1 = model.RpmBuild(
nvr='the-greatest-package-1.0.0-fc17.1',
package_id=self.package.id,
release_id=self.update.release.id,
)
build2 = model.RpmBuild(
nvr='the-greatest-package-1.1.0-fc17.1',
package_id=self.package.id,
release_id=self.update.release.id,
)
build1.update = self.update
build2.update = self.update
def test_backref_different_build_types(self):
"""Assert when builds differ in type and are set via backref validation passes."""
build1 = model.Build(
nvr='the-greatest-package-1.0.0-fc17.1',
package_id=self.package.id,
release_id=self.update.release.id,
)
build2 = model.RpmBuild(
nvr='the-greatest-package-1.1.0-fc17.1',
package_id=self.package.id,
release_id=self.update.release.id,
)
build1.update = self.update
with self.assertRaises(ValueError) as cm:
build2.update = self.update
self.assertEqual(str(cm.exception), u'An update must contain builds of the same type.')
class TestUpdate(ModelTest):
"""Unit test case for the ``Update`` model."""
klass = model.Update
attrs = dict(
title=u'TurboGears-1.0.8-3.fc11',
type=UpdateType.security,
status=UpdateStatus.pending,
request=UpdateRequest.testing,
severity=UpdateSeverity.medium,
suggest=UpdateSuggestion.reboot,
stable_karma=3,
unstable_karma=-3,
close_bugs=True,
notes=u'foobar',
test_gating_status=TestGatingStatus.passed)
def do_get_dependencies(self):
release = model.Release(**TestRelease.attrs)
return dict(
builds=[model.RpmBuild(
nvr=u'TurboGears-1.0.8-3.fc11', package=model.RpmPackage(**TestRpmPackage.attrs),
release=release)],
bugs=[model.Bug(bug_id=1), model.Bug(bug_id=2)],
cves=[model.CVE(cve_id=u'CVE-2009-0001')],
release=release,
user=model.User(name=u'lmacken'))
def get_update(self, name=u'TurboGears-1.0.8-3.fc11'):
"""Return an Update instance for testing."""
attrs = self.attrs.copy()
attrs['title'] = name
pkg = self.db.query(model.RpmPackage).filter_by(name=u'TurboGears').one()
rel = self.db.query(model.Release).filter_by(name=u'F11').one()
attrs.update(dict(
builds=[model.RpmBuild(nvr=name, package=pkg, release=rel)],
release=rel))
return self.klass(**attrs)
def test___json___with_no_builds(self):
"""Test the __json__() method when there are no Builds."""
self.obj.builds = []
self.assertEqual(self.obj.__json__()['content_type'], None)
@mock.patch('bodhi.server.models.log.warn')
def test_add_tag_null(self, warn):
"""Test the add_tag() method with a falsey tag, such as None."""
result = self.obj.add_tag(tag=None)
self.assertEqual(result, [])
warn.assert_called_once_with('Not adding builds of TurboGears-1.0.8-3.fc11 to empty tag')
def test_autokarma_not_nullable(self):
"""Assert that the autokarma column does not allow NULL values.
For history about why this is important, see
https://github.com/fedora-infra/bodhi/issues/1048
"""
self.assertEqual(model.Update.__table__.columns['autokarma'].nullable, False)
def test_builds(self):
self.assertEqual(len(self.obj.builds), 1)
self.assertEqual(self.obj.builds[0].nvr, u'TurboGears-1.0.8-3.fc11')
self.assertEqual(self.obj.builds[0].release.name, u'F11')
self.assertEqual(self.obj.builds[0].package.name, u'TurboGears')
def test_content_type(self):
self.assertEqual(self.obj.content_type, model.ContentType.rpm)
def test_greenwave_subject(self):
"""Ensure that the greenwave_subject property returns the correct value."""
self.obj.assign_alias()
self.assertEqual(
self.obj.greenwave_subject,
[{'item': u'TurboGears-1.0.8-3.fc11', 'type': 'koji_build'},
{'original_spec_nvr': u'TurboGears-1.0.8-3.fc11'},
{'item': self.obj.alias, 'type': 'bodhi_update'}])
def test_greenwave_subject_json(self):
"""Ensure that the greenwave_subject_json property returns the correct value."""
self.obj.assign_alias()
subject = self.obj.greenwave_subject_json
self.assertTrue(isinstance(subject, basestring))
self.assertEqual(
json.loads(subject),
[{'item': u'TurboGears-1.0.8-3.fc11', 'type': 'koji_build'},
{'original_spec_nvr': u'TurboGears-1.0.8-3.fc11'},
{'item': self.obj.alias, 'type': 'bodhi_update'}])
def test_mandatory_days_in_testing_critpath(self):
"""
The Update.mandatory_days_in_testing method should be the configured value
for critpath if it is a critpath update.
"""
update = self.obj
update.critpath = True
# Configured value.
expected = int(config.get('critpath.stable_after_days_without_negative_karma'))
self.assertEqual(update.mandatory_days_in_testing, expected)
def test_mandatory_days_in_testing(self):
"""
The Update.mandatory_days_in_testing method should be a positive integer if the
mandatory_days_in_testing attribute of release is not truthy.
"""
update = self.obj
self.assertEqual(update.mandatory_days_in_testing, 7)
@mock.patch.dict('bodhi.server.models.config', {'fedora.mandatory_days_in_testing': '0'})
def test_mandatory_days_in_testing_false(self):
"""
The Update.mandatory_days_in_testing method should be 0 if the
mandatory_days_in_testing attribute of release is not truthy.
"""
update = self.obj
self.assertEqual(update.mandatory_days_in_testing, 0)
def test_days_to_stable_critpath(self):
"""
The Update.days_to_stable() method should return a positive integer depending
on the configuration.
"""
update = self.get_update()
update.critpath = True
update.date_testing = datetime.utcnow() + timedelta(days=-4)
criptath_days_to_stable = int(
config.get('critpath.stable_after_days_without_negative_karma'))
self.assertEqual(update.days_to_stable, criptath_days_to_stable - 4)
def test_days_to_stable_meets_testing_requirements(self):
"""
The Update.days_to_stable() method should return 0 if Update.meets_testing_requirements()
returns True.
"""
update = self.obj
update.autokarma = False
update.stable_karma = 1
update.comment(self.db, u'I found $100 after applying this update.', karma=1,
author=u'bowlofeggs')
# Assert that our preconditions from the docblock are correct.
self.assertEqual(update.meets_testing_requirements, True)
self.assertEqual(update.days_to_stable, 0)
def test_days_to_stable_not_meets_testing_requirements_no_date_testing(self):
"""
The Update.days_to_stable() method should return 0 if Update.meets_testing_requirements()
returns False but the Update's date_testing attribute is not truthy.
"""
update = self.get_update()
# Assert that our preconditions from the docblock are correct.
self.assertEqual(update.meets_testing_requirements, False)
self.assertEqual(update.date_testing, None)
self.assertEqual(update.days_to_stable, 0)
def test_days_to_stable_not_meets_testing_requirements_with_date_testing(self):
"""
The Update.days_to_stable() method should return a positive integer if
Update.meets_testing_requirements() returns False and the Update's date_testing attribute is
truthy.
"""
update = self.get_update()
update.date_testing = datetime.utcnow() + timedelta(days=-4)
# Assert that our preconditions from the docblock are correct.
self.assertEqual(update.meets_testing_requirements, False)
self.assertEqual(update.days_to_stable, 3)
@mock.patch.dict('bodhi.server.config.config', {'test_gating.required': True})
def test_days_to_stable_zero(self):
"""
The Update.days_to_stable() method should only return a positive integer or zero.
In the past, days_to_stable() could return negative integers when the mandatory days in
testing was less than the number of days in testing. If the mandatory days in testing is
less than or equal to the number of days in testing, days_to_stable() should return zero.
See issue #1708.
"""
update = self.obj
update.autokarma = False
update.test_gating_status = TestGatingStatus.failed
update.date_testing = datetime.utcnow() + timedelta(days=-8)
self.assertEqual(update.meets_testing_requirements, False)
self.assertEqual(update.mandatory_days_in_testing <= update.days_in_testing, True)
self.assertEqual(update.days_to_stable, 0)
@mock.patch.dict('bodhi.server.config.config', {'test_gating.required': True})
def test_days_to_stable_positive(self):
"""
The Update.days_to_stable() method should only return a positive integer or zero.
In the past, days_to_stable() could return negative integers when the mandatory days in
testing was less than the number of days in testing. If the mandatory days in testing is
greater than the number of days in testing, return the positive number of days until
stable. See issue #1708.
"""
update = self.obj
update.autokarma = False
update.test_gating_status = TestGatingStatus.failed
update.date_testing = datetime.utcnow() + timedelta(days=-3)
self.assertEqual(update.meets_testing_requirements, False)
self.assertEqual(update.mandatory_days_in_testing > update.days_in_testing, True)
self.assertEqual(update.days_to_stable, 4)
@mock.patch.dict('bodhi.server.config.config', {'test_gating.required': True})
def test_test_gating_faild_no_testing_requirements(self):
"""
The Update.meets_testing_requirements() should return False, if the test gating
status of an update is failed.
"""
update = self.obj
update.autokarma = False
update.stable_karma = 1
update.test_gating_status = TestGatingStatus.failed
update.comment(self.db, u'I found $100 after applying this update.', karma=1,
author=u'bowlofeggs')
# Assert that our preconditions from the docblock are correct.
self.assertEqual(update.meets_testing_requirements, False)
@mock.patch.dict('bodhi.server.config.config', {'test_gating.required': True})
def test_test_gating_queued_no_testing_requirements(self):
"""
The Update.meets_testing_requirements() should return False, if the test gating
status of an update is queued.
"""
update = self.obj
update.autokarma = False
update.stable_karma = 1
update.test_gating_status = TestGatingStatus.queued
update.comment(self.db, u'I found $100 after applying this update.', karma=1,
author=u'bowlofeggs')
# Assert that our preconditions from the docblock are correct.
self.assertEqual(update.meets_testing_requirements, False)
@mock.patch.dict('bodhi.server.config.config', {'test_gating.required': True})
def test_test_gating_running_no_testing_requirements(self):
"""
The Update.meets_testing_requirements() should return False, if the test gating
status of an update is running.
"""
update = self.obj
update.autokarma = False
update.stable_karma = 1
update.test_gating_status = TestGatingStatus.running
update.comment(self.db, u'I found $100 after applying this update.', karma=1,
author=u'bowlofeggs')
# Assert that our preconditions from the docblock are correct.
self.assertEqual(update.meets_testing_requirements, False)
@mock.patch.dict('bodhi.server.config.config', {'test_gating.required': True})
def test_test_gating_missing_testing_requirements(self):
"""
The Update.meets_testing_requirements() should return True, if the test gating
status of an update is missing.
"""
update = self.obj
update.autokarma = False
update.stable_karma = 1
update.test_gating_status = None
update.comment(self.db, u'I found $100 after applying this update.', karma=1,
author=u'bowlofeggs')
# Assert that our preconditions from the docblock are correct.
self.assertEqual(update.meets_testing_requirements, True)
@mock.patch.dict('bodhi.server.config.config', {'test_gating.required': True})
def test_test_gating_waiting_testing_requirements(self):
"""
The Update.meets_testing_requirements() should return False, if the test gating
status of an update is waiting.
"""
update = self.obj
update.autokarma = False
update.stable_karma = 1
update.test_gating_status = TestGatingStatus.waiting
update.comment(self.db, u'I found $100 after applying this update.', karma=1,
author=u'bowlofeggs')
# Assert that our preconditions from the docblock are correct.
self.assertEqual(update.meets_testing_requirements, False)
@mock.patch.dict('bodhi.server.config.config', {'test_gating.required': False})
def test_test_gating_off(self):
"""
The Update.meets_testing_requirements() should return True if the
testing gating is not required, regardless of its test gating status.
"""
update = self.obj
update.autokarma = False
update.stable_karma = 1
update.test_gating_status = TestGatingStatus.running
update.comment(self.db, u'I found $100 after applying this update.', karma=1,
author=u'bowlofeggs')
# Assert that our preconditions from the docblock are correct.
self.assertEqual(update.meets_testing_requirements, True)
@mock.patch('bodhi.server.models.bugs.bugtracker.close')
@mock.patch('bodhi.server.models.bugs.bugtracker.comment')
def test_modify_bugs_stable_close(self, comment, close):
"""Test the modify_bugs() method with a stable status and with close_bugs set to True."""
update = self.get_update()
bug_1 = model.Bug(bug_id=1)
bug_2 = model.Bug(bug_id=2)
update.bugs.append(bug_1)
update.bugs.append(bug_2)
update.close_bugs = True
update.status = UpdateStatus.stable
update.modify_bugs()
# The comment call shouldn't have been made, since the comment should be included with the
# call to close().
self.assertEqual(comment.call_count, 0)
# Make sure close() was called correctly.
self.assertEqual([c[1][0] for c in close.mock_calls], [1, 2])
self.assertEqual(all(
['to the Fedora 11 stable repository' in c[2]['comment'] for c in close.mock_calls]),
True)
self.assertEqual(all(
[c[2]['versions']['TurboGears'] == 'TurboGears-1.0.8-3.fc11'
for c in close.mock_calls]),
True)
@mock.patch('bodhi.server.models.bugs.bugtracker.close')
@mock.patch('bodhi.server.models.bugs.bugtracker.comment')
def test_modify_bugs_stable_no_close(self, comment, close):
"""Test the modify_bugs() method with a stable status and with close_bugs set to False."""
update = self.get_update()
bug_1 = model.Bug(bug_id=1)
bug_2 = model.Bug(bug_id=2)
update.bugs.append(bug_1)
update.bugs.append(bug_2)
update.close_bugs = False
update.status = UpdateStatus.stable
update.modify_bugs()
# Make sure bugs number 1 and 2 were commented on correctly.
self.assertEqual([c[1][0] for c in comment.mock_calls], [1, 2])
self.assertEqual(all(
['pushed to the Fedora 11 stable repository' in c[1][1] for c in comment.mock_calls]),
True)
# No bugs should have been closed
self.assertEqual(close.call_count, 0)
@mock.patch('bodhi.server.util.requests.get')
@mock.patch.dict(util.config, {
'critpath.type': 'pdc',
'pdc_url': 'http://domain.local'
})
def test_contains_critpath_component(self, mock_get):
""" Verifies that the static function of contains_critpath_component
determines that one of the builds has a critpath component.
"""
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {
'count': 2,
'next': None,
'previous': None,
'results': [