forked from mozilla-releng/balrog
-
Notifications
You must be signed in to change notification settings - Fork 5
/
test_db.py
6174 lines (5592 loc) · 266 KB
/
test_db.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
import json
import logging
import os
import re
import sys
import unittest
from copy import deepcopy
from itertools import chain
from os import path
from tempfile import mkstemp
import migrate.versioning.api
import mock
import pytest
from migrate.versioning.api import version
from sqlalchemy import Column, Integer, MetaData, String, Table, create_engine, select
from sqlalchemy.engine.reflection import Inspector
import auslib
from auslib.blobs.apprelease import ReleaseBlobV1
from auslib.blobs.base import createBlob
from auslib.db import (
AlreadySetupError,
AUSDatabase,
AUSTable,
AUSTransaction,
ChangeScheduledError,
HistoryTable,
MismatchedDataVersionError,
OutdatedDataError,
PermissionDeniedError,
SignoffRequiredError,
SignoffsTable,
TransactionError,
UpdateMergeError,
verify_signoffs,
)
from auslib.errors import BlobValidationError, ReadOnlyError
from auslib.global_state import cache, dbo
from .fakes import FakeGCSHistory, FakeGCSHistoryAsync
def setUpModule():
# This is meant to silence the debug information coming from SQLAlchemy-Migrate since
# AUSDatabase provides decent debugging logs by itself.
logging.getLogger("migrate").setLevel(logging.CRITICAL)
class MemoryDatabaseMixin(object):
"""Use this when writing tests that don't require multiple connections to
the database."""
def setUp(self):
self.dburi = "sqlite:///:memory:"
class NamedFileDatabaseMixin(object):
"""Use this when writing tests that *do* require multiple connections to
the database. SQLite memory database don't support multiple connections
to the same database. When you try to use them, you get weird behaviour
like the second "connection" seeing the state of an in-progress
transaction in the first. See the following links for more detail:
http://www.sqlalchemy.org/docs/dialects/sqlite.html#threading-pooling-behavior
http://www.sqlalchemy.org/trac/wiki/FAQ#IamusingmultipleconnectionswithaSQLitedatabasetypicallytotesttransactionoperationandmytestprogramisnotworking
"""
def setUp(self):
self.tmpfiles = []
self.dburi = "sqlite:///%s" % self.getTempfile()
def tearDown(self):
for fd, t in self.tmpfiles:
os.close(fd)
os.remove(t)
def getTempfile(self):
fd, t = mkstemp()
self.tmpfiles.append((fd, t))
return t
class TestVerifySignoffs(unittest.TestCase):
def testNoRequiredSignoffs(self):
verify_signoffs({}, {})
def testNoRequiredSignoffsWithSignoffs(self):
verify_signoffs({}, [{"role": "releng"}, {"role": "relman"}])
def testNoSignoffsGiven(self):
required = [{"role": "releng", "signoffs_required": 1}]
signoffs = []
self.assertRaises(SignoffRequiredError, verify_signoffs, required, signoffs)
def testMissingSignoffFromOneRole(self):
required = [{"role": "releng", "signoffs_required": 1}, {"role": "relman", "signoffs_required": 1}]
signoffs = [{"role": "releng", "username": "joe"}]
self.assertRaises(SignoffRequiredError, verify_signoffs, required, signoffs)
def testNotEnoughSignoffsFromOneRole(self):
required = [{"role": "releng", "signoffs_required": 2}, {"role": "relman", "signoffs_required": 1}]
signoffs = [{"role": "releng", "username": "joe"}, {"role": "relman", "username": "jane"}]
self.assertRaises(SignoffRequiredError, verify_signoffs, required, signoffs)
def testExactlyEnoughSignoffsGiven(self):
required = [{"role": "releng", "signoffs_required": 2}, {"role": "relman", "signoffs_required": 1}]
signoffs = [{"role": "releng", "username": "joe"}, {"role": "releng", "username": "jane"}, {"role": "relman", "username": "nick"}]
verify_signoffs(required, signoffs)
def testMoreThanEnoughSignoffsGiven(self):
required = [{"role": "releng", "signoffs_required": 2}, {"role": "relman", "signoffs_required": 1}]
signoffs = [
{"role": "releng", "username": "joe"},
{"role": "releng", "username": "jane"},
{"role": "relman", "username": "nick"},
{"role": "relman", "username": "matt"},
]
verify_signoffs(required, signoffs)
def testMultiplePotentialSignoffsForOneGroupWithoutEnoughSignoffs(self):
required = [{"role": "releng", "signoffs_required": 2}, {"role": "releng", "signoffs_required": 1}, {"role": "relman", "signoffs_required": 1}]
signoffs = [{"role": "releng", "username": "joe"}, {"role": "relman", "username": "nick"}]
self.assertRaises(SignoffRequiredError, verify_signoffs, required, signoffs)
def testMultiplePotentialSignoffsForOneGroupWithEnoughSignoffs(self):
required = [{"role": "releng", "signoffs_required": 2}, {"role": "releng", "signoffs_required": 1}, {"role": "relman", "signoffs_required": 1}]
signoffs = [{"role": "releng", "username": "joe"}, {"role": "releng", "username": "jane"}, {"role": "relman", "username": "nick"}]
verify_signoffs(required, signoffs)
class TestAUSTransaction(unittest.TestCase, MemoryDatabaseMixin):
def setUp(self):
MemoryDatabaseMixin.setUp(self)
self.engine = create_engine(self.dburi)
self.metadata = MetaData(self.engine)
self.table = Table("test", self.metadata, Column("id", Integer, primary_key=True), Column("foo", Integer))
self.metadata.create_all()
self.table.insert().execute(id=1, foo=33)
self.table.insert().execute(id=2, foo=22)
self.table.insert().execute(id=3, foo=11)
def testTransaction(self):
trans = AUSTransaction(self.metadata.bind.connect())
trans.execute(self.table.insert(values=dict(id=4, foo=55)))
trans.execute(self.table.update(values=dict(foo=66)).where(self.table.c.id == 1))
trans.commit()
ret = self.table.select().execute().fetchall()
self.assertEqual(ret, [(1, 66), (2, 22), (3, 11), (4, 55)])
def testTransactionRaisesOnError(self):
trans = AUSTransaction(self.metadata.bind.connect())
self.assertRaises(TransactionError, trans.execute, "UPDATE test SET foo=123 WHERE fake=1")
def testRollback(self):
trans = AUSTransaction(self.metadata.bind.connect())
trans.execute(self.table.update(values=dict(foo=66)).where(self.table.c.id == 1))
trans.rollback()
ret = self.table.select().execute().fetchall()
self.assertEqual(ret, [(1, 33), (2, 22), (3, 11)])
# bug 740360
def testContextManagerClosesConnection(self):
with AUSTransaction(self.metadata.bind.connect()) as trans:
self.assertEqual(trans.conn.closed, False, "Connection closed at start of transaction, expected it to be open.")
trans.execute(self.table.insert(values=dict(id=5, foo=41)))
self.assertEqual(trans.conn.closed, True, "Connection not closed after __exit__ is called")
class TestAUSTransactionRequiresRealFile(unittest.TestCase, NamedFileDatabaseMixin):
def setUp(self):
NamedFileDatabaseMixin.setUp(self)
self.engine = create_engine(self.dburi)
self.metadata = MetaData(self.engine)
self.table = Table("test", self.metadata, Column("id", Integer, primary_key=True), Column("foo", Integer))
self.metadata.create_all()
self.table.insert().execute(id=1, foo=33)
self.table.insert().execute(id=2, foo=22)
self.table.insert().execute(id=3, foo=11)
def testTransactionNotChangedUntilCommit(self):
trans = AUSTransaction(self.metadata.bind.connect())
trans.execute(self.table.update(values=dict(foo=66)).where(self.table.c.id == 1))
# This select() runs in a different connection, so no changes should
# be visible to it yet
ret = self.table.select().execute().fetchall()
self.assertEqual(ret, [(1, 33), (2, 22), (3, 11)])
trans.commit()
ret = self.table.select().execute().fetchall()
self.assertEqual(ret, [(1, 66), (2, 22), (3, 11)])
class TestTableMixin(object):
def setUp(self):
self.engine = create_engine(self.dburi)
self.metadata = MetaData(self.engine)
class TestTable(AUSTable):
def __init__(self, db, metadata):
self.table = Table("test", metadata, Column("id", Integer, primary_key=True, autoincrement=True), Column("foo", Integer))
AUSTable.__init__(self, db, "sqlite", historyClass=HistoryTable)
class TestAutoincrementTable(AUSTable):
def __init__(self, db, metadata):
self.table = Table("test-autoincrement", metadata, Column("id", Integer, primary_key=True, autoincrement=True), Column("foo", Integer))
AUSTable.__init__(self, db, "sqlite", historyClass=HistoryTable)
self.test = TestTable("fake", self.metadata)
self.testAutoincrement = TestAutoincrementTable("fake", self.metadata)
self.metadata.create_all()
self.test.t.insert().execute(id=1, foo=33, data_version=4)
self.test.t.insert().execute(id=2, foo=22, data_version=5)
self.test.t.insert().execute(id=3, foo=11, data_version=6)
self.test.history.t.insert().execute(change_id=1, timestamp=9, changed_by="admin", id=1)
self.test.history.t.insert().execute(change_id=2, timestamp=10, changed_by="admin", id=1, foo=30, data_version=1)
self.test.history.t.insert().execute(change_id=3, timestamp=20, changed_by="admin", id=1, foo=31, data_version=2)
self.test.history.t.insert().execute(change_id=4, timestamp=30, changed_by="admin", id=1, foo=32, data_version=3)
self.test.history.t.insert().execute(change_id=5, timestamp=40, changed_by="admin", id=1, foo=33, data_version=4)
self.test.history.t.insert().execute(change_id=6, timestamp=9, changed_by="admin", id=2)
self.test.history.t.insert().execute(change_id=7, timestamp=10, changed_by="admin", id=2, foo=18, data_version=1)
self.test.history.t.insert().execute(change_id=8, timestamp=15, changed_by="admin", id=2, foo=19, data_version=2)
self.test.history.t.insert().execute(change_id=9, timestamp=20, changed_by="admin", id=2, foo=20, data_version=3)
self.test.history.t.insert().execute(change_id=10, timestamp=25, changed_by="admin", id=2, foo=21, data_version=4)
self.test.history.t.insert().execute(change_id=11, timestamp=30, changed_by="admin", id=2, foo=22, data_version=5)
self.test.history.t.insert().execute(change_id=12, timestamp=22, changed_by="admin", id=3)
self.test.history.t.insert().execute(change_id=13, timestamp=23, changed_by="admin", id=3, foo=6, data_version=1)
self.test.history.t.insert().execute(change_id=14, timestamp=26, changed_by="admin", id=3, foo=7, data_version=2)
self.test.history.t.insert().execute(change_id=15, timestamp=29, changed_by="admin", id=3, foo=8, data_version=3)
self.test.history.t.insert().execute(change_id=16, timestamp=32, changed_by="admin", id=3, foo=9, data_version=4)
self.test.history.t.insert().execute(change_id=17, timestamp=35, changed_by="admin", id=3, foo=10, data_version=5)
self.test.history.t.insert().execute(change_id=18, timestamp=38, changed_by="admin", id=3, foo=11, data_version=6)
self.test.history.t.insert().execute(change_id=19, timestamp=19, changed_by="admin", id=4)
self.test.history.t.insert().execute(change_id=20, timestamp=20, changed_by="admin", id=4, foo=40, data_version=1)
self.test.history.t.insert().execute(change_id=21, timestamp=25, changed_by="admin", id=4, foo=41, data_version=2)
self.test.history.t.insert().execute(change_id=22, timestamp=30, changed_by="admin", id=4, foo=42, data_version=3)
self.test.history.t.insert().execute(change_id=23, timestamp=35, changed_by="admin", id=4)
class TestMultiplePrimaryTableMixin(object):
def setUp(self):
self.engine = create_engine(self.dburi)
self.metadata = MetaData(self.engine)
class TestTable(AUSTable):
def __init__(self, db, metadata):
self.table = Table(
"test",
metadata,
Column("id1", Integer, primary_key=True, autoincrement=False),
Column("id2", Integer, primary_key=True, autoincrement=False),
Column("foo", Integer),
)
AUSTable.__init__(self, db, "sqlite", historyClass=HistoryTable)
self.test = TestTable("fake", self.metadata)
self.metadata.create_all()
self.test.t.insert().execute(id1=1, id2=1, foo=33, data_version=1)
self.test.t.insert().execute(id1=1, id2=2, foo=22, data_version=1)
self.test.t.insert().execute(id1=2, id2=1, foo=11, data_version=1)
self.test.t.insert().execute(id1=2, id2=2, foo=44, data_version=1)
class TestAUSTable(unittest.TestCase, TestTableMixin, MemoryDatabaseMixin):
def setUp(self):
MemoryDatabaseMixin.setUp(self)
TestTableMixin.setUp(self)
def testColumnMirroring(self):
self.assertTrue(self.test.id in self.test.table.get_children())
self.assertTrue(self.test.foo in self.test.table.get_children())
def testSelect(self):
expected = [dict(id=1, foo=33, data_version=4), dict(id=2, foo=22, data_version=5), dict(id=3, foo=11, data_version=6)]
self.assertEqual(self.test.select(), expected)
def testSelectWithColumns(self):
expected = [dict(id=1), dict(id=2), dict(id=3)]
self.assertEqual(self.test.select(columns=[self.test.id]), expected)
def testSelectWithWhere(self):
expected = [dict(id=2, foo=22, data_version=5), dict(id=3, foo=11, data_version=6)]
self.assertEqual(self.test.select(where=[self.test.id >= 2]), expected)
def testSelectWithOrder(self):
expected = [dict(id=3, foo=11, data_version=6), dict(id=2, foo=22, data_version=5), dict(id=1, foo=33, data_version=4)]
self.assertEqual(self.test.select(order_by=[self.test.foo]), expected)
def testSelectWithLimit(self):
self.assertEqual(self.test.select(limit=1), [dict(id=1, foo=33, data_version=4)])
def testSelectCanModifyResult(self):
ret = self.test.select()[0]
# If we can't write to this, an Exception will be raised and the test will fail
ret["foo"] = 3245
def testInsert(self):
self.test.insert(changed_by="bob", id=5, foo=0)
ret = self.test.t.select().execute().fetchall()
self.assertEqual(len(ret), 4)
self.assertEqual(ret[-1], (5, 0, 1))
def testInsertClosesConnectionOnImplicitTransaction(self):
with mock.patch("sqlalchemy.engine.base.Connection.close") as close:
self.test.insert(changed_by="bob", id=5, foo=1)
self.assertTrue(close.called, "Connection.close() never called by insert()")
def testInsertClosesConnectionOnImplicitTransactionWithError(self):
with mock.patch("sqlalchemy.engine.base.Connection.close") as close:
try:
self.test.insert(changed_by="bob", id=1, foo=1)
except Exception:
pass
self.assertTrue(close.called, "Connection.close() never called by insert()")
def testInsertWithChangeCallback(self):
shared = []
self.test.onInsert = lambda *x, **y: shared.extend(x)
what = {"id": 5, "foo": 1}
self.test.insert(changed_by="bob", **what)
# insert adds data_version to the query, so we need to add that before comparing
what["data_version"] = 1
self.assertEqual(shared[0], self.test)
self.assertEqual(shared[1], "INSERT")
self.assertEqual(shared[2], "bob")
self.assertEqual(shared[3].parameters, what)
def testDelete(self):
ret = self.test.delete(changed_by="bill", where=[self.test.id == 1, self.test.foo == 33], old_data_version=4)
self.assertEqual(ret.rowcount, 1)
self.assertEqual(len(self.test.t.select().execute().fetchall()), 2)
def testDeleteFailsOnVersionMismatch(self):
self.assertRaises(OutdatedDataError, self.test.delete, changed_by="bill", where=[self.test.id == 3], old_data_version=1)
def testDeleteClosesConnectionOnImplicitTransaction(self):
with mock.patch("sqlalchemy.engine.base.Connection.close") as close:
self.test.delete(changed_by="bill", where=[self.test.id == 1], old_data_version=4)
self.assertTrue(close.called, "Connection.close() never called by delete()")
def testDeleteWithChangeCallback(self):
shared = []
self.test.onDelete = lambda *x: shared.extend(x)
where = [self.test.id == 1]
self.test.delete(changed_by="bob", where=where, old_data_version=4)
# update adds data_version and id to the query, so we need to add that before comparing
self.assertEqual(shared[0], self.test)
self.assertEqual(shared[1], "DELETE")
self.assertEqual(shared[2], "bob")
# There should be two WHERE clauses, because AUSTable adds a data_version one in addition
# to the id condition above.
self.assertEqual(len(shared[3]._whereclause.get_children()), 2)
def testUpdate(self):
ret = self.test.update(changed_by="bob", where=[self.test.id == 1], what=dict(foo=123), old_data_version=4)
self.assertEqual(ret.rowcount, 1)
self.assertEqual(self.test.t.select(self.test.id == 1).execute().fetchone(), (1, 123, 5))
def testUpdateFailsOnVersionMismatch(self):
self.assertRaises(OutdatedDataError, self.test.update, changed_by="bill", where=[self.test.id == 3], what=dict(foo=99), old_data_version=1)
def testUpdateClosesConnectionOnImplicitTransaction(self):
with mock.patch("sqlalchemy.engine.base.Connection.close") as close:
self.test.update(changed_by="bob", where=[self.test.id == 1], what=dict(foo=432), old_data_version=4)
self.assertTrue(close.called, "Connection.close() never called by update()")
def testUpdateWithChangeCallback(self):
shared = []
def onUpdate(*args, **kwargs):
shared.extend(args)
for _, v in kwargs.items():
shared.append(v)
self.test.onUpdate = onUpdate
where = [self.test.id == 1]
what = dict(foo=123)
additional_columns = dict(bar=42)
self.test.update(changed_by="bob", where=where, what=dict(chain(what.items(), additional_columns.items())), old_data_version=4)
# update adds data_version and id to the query, so we need to add that before comparing
what["data_version"] = 5
what["id"] = 1
self.assertEqual(shared[0], self.test)
self.assertEqual(shared[1], "UPDATE")
self.assertEqual(shared[2], "bob")
self.assertEqual(shared[3].parameters, what)
self.assertIsInstance(shared[4], AUSTransaction)
self.assertEqual(shared[5], additional_columns)
# There should be two WHERE clauses, because AUSTable adds a data_version one in addition
# to the id condition above.
self.assertEqual(len(shared[3]._whereclause.get_children()), 2)
def test_count(self):
count = self.test.count()
self.assertEqual(count, 3)
where = [self.test.id == 2]
count = self.test.count(where=where)
self.assertEqual(count, 1)
where = [self.test.id == -1]
count = self.test.count(where=where)
self.assertEqual(count, 0)
class TestAUSTableRequiresRealFile(unittest.TestCase, TestTableMixin, NamedFileDatabaseMixin):
def setUp(self):
NamedFileDatabaseMixin.setUp(self)
TestTableMixin.setUp(self)
def testDeleteWithTransaction(self):
trans = AUSTransaction(self.metadata.bind.connect())
self.test.delete(changed_by="bill", transaction=trans, where=[self.test.id == 2], old_data_version=5)
ret = self.test.t.select().execute().fetchall()
self.assertEqual(len(ret), 3)
trans.commit()
ret = self.test.t.select().execute().fetchall()
self.assertEqual(len(ret), 2)
def testInsertWithTransaction(self):
trans = AUSTransaction(self.metadata.bind.connect())
self.test.insert(changed_by="bob", transaction=trans, id=5, foo=1)
ret = self.test.t.select().execute().fetchall()
self.assertEqual(len(ret), 3)
trans.commit()
ret = self.test.t.select().execute().fetchall()
self.assertEqual(ret[-1], (5, 1, 1))
def testUpdateWithTransaction(self):
trans = AUSTransaction(self.metadata.bind.connect())
self.test.update(changed_by="bill", transaction=trans, where=[self.test.id == 1], what=dict(foo=222), old_data_version=4)
ret = self.test.t.select(self.test.id == 1).execute().fetchone()
self.assertEqual(ret, (1, 33, 4))
trans.commit()
ret = self.test.t.select(self.test.id == 1).execute().fetchone()
self.assertEqual(ret, (1, 222, 5))
# TODO: Find some way of testing this with SQLite, or testing it with some other backend.
# Because it's impossible to have multiple simultaneous transaction with sqlite, you
# can't test the behaviour of concurrent transactions with it.
# def testUpdateCollidingUpdateFails(self):
# trans1 = AUSTransaction(self.test.getEngine().connect())
# trans2 = AUSTransaction(self.test.getEngine().connect())
# ret1 = self.test._prepareUpdate(trans1, where=[self.test.id==3], what=dict(foo=99), changed_by='bob')
# ret2 = self.test._prepareUpdate(trans2, where=[self.test.id==3], what=dict(foo=66), changed_by='bob')
# trans1.commit()
# self.assertEqual(ret1.rowcount, 1)
# self.assertEqual(self.test.t.select(self.test.id==3).execute().fetchone(), (1, 99, 2))
# self.assertRaises(TransactionError, trans2.commit)
class TestHistoryTable(unittest.TestCase, TestTableMixin, MemoryDatabaseMixin):
maxDiff = 2000
def setUp(self):
MemoryDatabaseMixin.setUp(self)
TestTableMixin.setUp(self)
def testHasHistoryTable(self):
self.assertTrue(self.test.history)
def testHistoryTableHasAllColumns(self):
columns = [c.name for c in self.test.history.t.get_children()]
self.assertTrue("change_id" in columns)
self.assertTrue("id" in columns)
self.assertTrue("foo" in columns)
self.assertTrue("changed_by" in columns)
self.assertTrue("timestamp" in columns)
self.assertTrue("data_version" in columns)
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testHistoryUponInsert(self):
self.test.insert(changed_by="george", id=5, foo=0)
ret = self.test.history.t.select().where(self.test.history.id == 5).execute().fetchall()
self.assertEqual(ret, [(24, "george", 999, 5, None, None), (25, "george", 1000, 5, 0, 1)])
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testHistoryUponAutoincrementInsert(self):
self.test.insert(changed_by="george", foo=0)
# This actual generates history for a row we already have history for
# because sqlite just uses max(id)+1 as the next available primary key.
# Even if we insert and delete id 4 from the database, we still
# get id=4 for the next autoincrement insert.
ret = self.test.history.t.select().where(self.test.history.id == 4).execute().fetchall()[-2:]
self.assertEqual(ret, [(24, "george", 999, 4, None, None), (25, "george", 1000, 4, 0, 1)])
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testHistoryUponDelete(self):
self.test.delete(changed_by="bobby", where=[self.test.id == 1], old_data_version=4)
ret = self.test.history.t.select().where(self.test.history.id == 1).execute().fetchall()[-1]
self.assertEqual(ret, (24, "bobby", 1000, 1, None, None))
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testHistoryUponUpdate(self):
self.test.update(changed_by="heather", where=[self.test.id == 2], what=dict(foo=99), old_data_version=5)
ret = self.test.history.t.select().where(self.test.history.id == 2).execute().fetchall()[-1]
self.assertEqual(ret, (24, "heather", 1000, 2, 99, 6))
@mock.patch("time.time", mock.MagicMock(return_value=1234567890.123456))
def testHistoryTimestampMaintainsPrecision(self):
self.test.insert(changed_by="bob", id=5)
ret = select([self.test.history.timestamp]).where(self.test.history.id == 5).execute().fetchone()[0]
# Insert decrements the timestamp
self.assertEqual(ret, 1234567890122)
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testHistoryGetChangeWithChangeID(self):
self.test.insert(changed_by="george", id=5, foo=0)
ret = self.test.history.getChange(change_id=24)
self.assertEqual(ret, {"data_version": None, "changed_by": "george", "foo": None, "timestamp": 999, "change_id": 24, "id": 5})
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testHistoryGetChangeWithDataVersion(self):
self.test.insert(changed_by="george", id=5, foo=0)
ret = self.test.history.getChange(data_version=1, column_values={"id": 5})
self.assertEqual(ret, {"data_version": 1, "changed_by": "george", "foo": 0, "timestamp": 1000, "change_id": 25, "id": 5})
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testHistoryGetChangeWithDataVersionReturnNone(self):
self.test.insert(changed_by="george", id=5, foo=0)
ret = self.test.history.getChange(data_version=1, column_values={"id": 6})
self.assertEqual(ret, None)
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testHistoryGetChangeWithDataVersionWithNonPrimaryKeyColumn(self):
self.test.insert(changed_by="george", id=5, foo=0)
self.assertRaises(ValueError, self.test.history.getChange, data_version=1, column_values={"foo": 5})
def testGetPointInTime(self):
times_and_results = (
(
10,
(
dict(change_id=2, timestamp=10, changed_by="admin", id=1, foo=30, data_version=1),
dict(change_id=7, timestamp=10, changed_by="admin", id=2, foo=18, data_version=1),
),
),
(
15,
(
dict(change_id=2, timestamp=10, changed_by="admin", id=1, foo=30, data_version=1),
dict(change_id=8, timestamp=15, changed_by="admin", id=2, foo=19, data_version=2),
),
),
(
20,
(
dict(change_id=3, timestamp=20, changed_by="admin", id=1, foo=31, data_version=2),
dict(change_id=9, timestamp=20, changed_by="admin", id=2, foo=20, data_version=3),
dict(change_id=20, timestamp=20, changed_by="admin", id=4, foo=40, data_version=1),
),
),
(
25,
(
dict(change_id=3, timestamp=20, changed_by="admin", id=1, foo=31, data_version=2),
dict(change_id=10, timestamp=25, changed_by="admin", id=2, foo=21, data_version=4),
dict(change_id=13, timestamp=23, changed_by="admin", id=3, foo=6, data_version=1),
dict(change_id=21, timestamp=25, changed_by="admin", id=4, foo=41, data_version=2),
),
),
(
30,
(
dict(change_id=4, timestamp=30, changed_by="admin", id=1, foo=32, data_version=3),
dict(change_id=11, timestamp=30, changed_by="admin", id=2, foo=22, data_version=5),
dict(change_id=15, timestamp=29, changed_by="admin", id=3, foo=8, data_version=3),
dict(change_id=22, timestamp=30, changed_by="admin", id=4, foo=42, data_version=3),
),
),
(
35,
(
dict(change_id=4, timestamp=30, changed_by="admin", id=1, foo=32, data_version=3),
dict(change_id=11, timestamp=30, changed_by="admin", id=2, foo=22, data_version=5),
dict(change_id=17, timestamp=35, changed_by="admin", id=3, foo=10, data_version=5),
),
),
(
40,
(
dict(change_id=5, timestamp=40, changed_by="admin", id=1, foo=33, data_version=4),
dict(change_id=11, timestamp=30, changed_by="admin", id=2, foo=22, data_version=5),
dict(change_id=18, timestamp=38, changed_by="admin", id=3, foo=11, data_version=6),
),
),
)
for timestamp, expected in times_and_results:
ret = self.test.history.getPointInTime(timestamp)
self.assertSequenceEqual(ret, expected)
class TestMultiplePrimaryHistoryTable(unittest.TestCase, TestMultiplePrimaryTableMixin, MemoryDatabaseMixin):
def setUp(self):
MemoryDatabaseMixin.setUp(self)
TestMultiplePrimaryTableMixin.setUp(self)
def testHasHistoryTable(self):
self.assertTrue(self.test.history)
def testMultiplePrimaryHistoryTableHasAllColumns(self):
columns = [c.name for c in self.test.history.t.get_children()]
self.assertTrue("change_id" in columns)
self.assertTrue("id1" in columns)
self.assertTrue("id2" in columns)
self.assertTrue("foo" in columns)
self.assertTrue("changed_by" in columns)
self.assertTrue("timestamp" in columns)
self.assertTrue("data_version" in columns)
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testMultiplePrimaryHistoryUponInsert(self):
self.test.insert(changed_by="george", id1=4, id2=5, foo=0)
ret = self.test.history.t.select().execute().fetchall()
self.assertEqual(ret, [(1, "george", 999, 4, 5, None, None), (2, "george", 1000, 4, 5, 0, 1)])
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testMultiplePrimaryHistoryUponDelete(self):
self.test.delete(changed_by="bobby", where=[self.test.id1 == 1, self.test.id2 == 2], old_data_version=1)
ret = self.test.history.t.select().execute().fetchone()
self.assertEqual(ret, (1, "bobby", 1000, 1, 2, None, None))
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testMultiplePrimaryHistoryUponUpdate(self):
self.test.update(changed_by="heather", where=[self.test.id1 == 2, self.test.id2 == 1], what=dict(foo=99), old_data_version=1)
ret = self.test.history.t.select().execute().fetchone()
self.assertEqual(ret, (1, "heather", 1000, 2, 1, 99, 2))
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testMultiplePrimaryKeyHistoryGetChangeWithDataVersion(self):
self.test.insert(changed_by="george", id1=4, id2=5, foo=0)
ret = self.test.history.getChange(data_version=1, column_values={"id1": 4, "id2": 5})
self.assertEqual(ret, {"data_version": 1, "changed_by": "george", "foo": 0, "timestamp": 1000, "change_id": 2, "id1": 4, "id2": 5})
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testMultiplePrimaryKeyHistoryGetChangeWithDataVersionReturnNone(self):
self.test.insert(changed_by="george", id1=4, id2=5, foo=0)
ret = self.test.history.getChange(data_version=1, column_values={"id1": 4, "id2": 55})
self.assertEqual(ret, None)
@mock.patch("time.time", mock.MagicMock(return_value=1.0))
def testHistoryGetChangeWithDataVersionWithNonPrimaryKeyColumn(self):
self.test.insert(changed_by="george", id1=4, id2=5, foo=0)
self.assertRaises(ValueError, self.test.history.getChange, data_version=1, column_values={"id1": 4, "foo": 4})
@pytest.mark.usefixtures("current_db_schema")
class ScheduledChangesTableMixin(object):
def setUp(self):
self.db = AUSDatabase(self.dburi, releases_history_buckets={"*": "fake"}, releases_history_class=FakeGCSHistory)
self.metadata.create_all(self.db.engine)
self.engine = self.db.engine
self.metadata = self.db.metadata
class TestTable(AUSTable):
def __init__(self, db, metadata):
self.table = Table(
"test_table",
metadata,
Column("fooid", Integer, primary_key=True, autoincrement=True),
Column("foo", String(15), nullable=False),
Column("bar", String(15)),
)
super(TestTable, self).__init__(db, "sqlite", scheduled_changes=True, versioned=True, historyClass=HistoryTable)
def getPotentialRequiredSignoffs(self, affected_rows, transaction=None):
for row in affected_rows:
if row["foo"] == "signofftest":
return {"rs": [{"role": "releng", "signoffs_required": 1}]}
def insert(self, changed_by, transaction=None, dryrun=False, signoffs=None, **columns):
if not self.db.hasPermission(changed_by, "test", "create", transaction=transaction):
raise PermissionDeniedError("fail")
if not dryrun:
super(TestTable, self).insert(changed_by, transaction, dryrun, **columns)
def update(self, where, what, changed_by, old_data_version, transaction=None, dryrun=False, signoffs=None):
# Although our test table doesn't need it, real tables do some extra permission
# checks based on "where". To make sure we catch bugs around the "where" arg
# being broken, we use it similarly here.
for row in self.select(where=where, transaction=transaction):
if not self.db.hasPermission(changed_by, "test", "modify", transaction=transaction):
raise PermissionDeniedError("fail")
if not dryrun:
super(TestTable, self).update(where, what, changed_by, old_data_version, transaction, dryrun)
def delete(self, where, changed_by, old_data_version, transaction=None, dryrun=False, signoffs=None):
if not self.db.hasPermission(changed_by, "test", "delete", transaction=transaction):
raise PermissionDeniedError("fail")
if not dryrun:
super(TestTable, self).delete(where, changed_by, old_data_version, transaction, dryrun)
self.table = TestTable(self.db, self.metadata)
self.sc_table = self.table.scheduled_changes
self.metadata.create_all()
self.table.t.insert().execute(fooid=1, foo="a", data_version=1)
self.table.t.insert().execute(fooid=2, foo="b", bar="bb", data_version=2)
self.table.t.insert().execute(fooid=3, foo="c", data_version=2)
self.table.t.insert().execute(fooid=4, foo="d", data_version=2)
self.sc_table.t.insert().execute(
sc_id=1, scheduled_by="bob", base_fooid=1, base_foo="aa", base_bar="barbar", base_data_version=1, data_version=1, change_type="update"
)
self.sc_table.conditions.t.insert().execute(sc_id=1, when=234000, data_version=1)
self.sc_table.t.insert().execute(sc_id=2, scheduled_by="bob", base_foo="cc", base_bar="ceecee", data_version=1, change_type="insert")
self.sc_table.conditions.t.insert().execute(sc_id=2, when=567000, data_version=1)
self.sc_table.t.insert().execute(
sc_id=3, scheduled_by="bob", complete=True, base_fooid=2, base_foo="b", base_bar="bb", base_data_version=1, data_version=1, change_type="update"
)
self.sc_table.conditions.t.insert().execute(sc_id=3, when=1000, data_version=1)
self.sc_table.t.insert().execute(
sc_id=4, scheduled_by="bob", base_fooid=2, base_foo="dd", base_bar="bb", base_data_version=2, data_version=1, change_type="update"
)
self.sc_table.conditions.t.insert().execute(sc_id=4, when=333000, data_version=1)
self.sc_table.t.insert().execute(
sc_id=5, scheduled_by="bob", complete=True, base_fooid=3, base_foo="c", base_bar="bb", base_data_version=1, data_version=1, change_type="update"
)
self.sc_table.conditions.t.insert().execute(sc_id=5, when=39000, data_version=1)
self.sc_table.t.insert().execute(
sc_id=6, scheduled_by="bob", complete=False, base_fooid=4, base_foo="d", base_bar=None, base_data_version=2, data_version=1, change_type="delete"
)
self.sc_table.conditions.t.insert().execute(sc_id=6, when=400000, data_version=1)
self.db.permissions.t.insert().execute(permission="admin", username="bob", data_version=1)
self.db.permissions.t.insert().execute(permission="admin", username="mary", data_version=1)
self.db.permissions.t.insert().execute(permission="admin", username="jane", data_version=1)
self.db.permissions.t.insert().execute(permission="scheduled_change", username="nancy", options={"actions": ["enact"]}, data_version=1)
self.db.permissions.user_roles.t.insert().execute(username="bob", role="releng", data_version=1)
self.db.permissions.user_roles.t.insert().execute(username="mary", role="releng", data_version=1)
self.db.permissions.user_roles.t.insert().execute(username="mary", role="dev", data_version=1)
self.db.permissions.user_roles.t.insert().execute(username="jane", role="dev", data_version=1)
class TestScheduledChangesTable(unittest.TestCase, ScheduledChangesTableMixin, MemoryDatabaseMixin):
def setUp(self):
MemoryDatabaseMixin.setUp(self)
ScheduledChangesTableMixin.setUp(self)
def testAllTablesCreated(self):
self.assertTrue(self.table)
self.assertTrue(self.table.history)
self.assertTrue(self.table.scheduled_changes)
self.assertTrue(self.table.scheduled_changes.history)
self.assertTrue(self.table.scheduled_changes.conditions)
self.assertTrue(self.table.scheduled_changes.conditions.history)
self.assertTrue(self.table.scheduled_changes.signoffs)
self.assertTrue(self.table.scheduled_changes.signoffs.history)
def testTablesHaveCorrectColumns(self):
sc_columns = [c.name for c in self.sc_table.t.get_children()]
self.assertEqual(len(sc_columns), 9)
self.assertTrue("sc_id" in sc_columns)
self.assertTrue("scheduled_by" in sc_columns)
self.assertTrue("complete" in sc_columns)
self.assertTrue("data_version" in sc_columns)
self.assertTrue("base_fooid" in sc_columns)
self.assertTrue("base_foo" in sc_columns)
self.assertTrue("base_bar" in sc_columns)
self.assertTrue("base_data_version" in sc_columns)
self.assertTrue("change_type" in sc_columns)
self.assertTrue("telemetry_product" not in sc_columns)
self.assertTrue("telemetry_channel" not in sc_columns)
self.assertTrue("telemetry_uptake" not in sc_columns)
self.assertTrue("when" not in sc_columns)
cond_columns = [c.name for c in self.sc_table.conditions.t.get_children()]
self.assertEqual(len(cond_columns), 6)
self.assertTrue("sc_id" in cond_columns)
self.assertTrue("telemetry_product" in cond_columns)
self.assertTrue("telemetry_channel" in cond_columns)
self.assertTrue("telemetry_uptake" in cond_columns)
self.assertTrue("when" in cond_columns)
self.assertTrue("data_version" in cond_columns)
signoff_columns = [c.name for c in self.sc_table.signoffs.t.get_children()]
self.assertTrue("sc_id" in signoff_columns)
self.assertTrue("username" in signoff_columns)
self.assertTrue("role" in signoff_columns)
def testValidateConditionsNone(self):
self.assertRaisesRegex(ValueError, "No conditions found", self.sc_table.conditions.validate, {})
def testValidateConditionsNoneValue(self):
self.assertRaisesRegex(ValueError, "No conditions found", self.sc_table.conditions.validate, {"when": None})
def testValdiateConditionsInvalid(self):
self.assertRaisesRegex(ValueError, "Invalid condition", self.sc_table.conditions.validate, {"blah": "blah"})
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testValidateConditionsJustWhen(self):
self.sc_table.conditions.validate({"when": 12345678})
def testValidateConditionsBadWhen(self):
self.assertRaisesRegex(ValueError, "Cannot parse", self.sc_table.conditions.validate, {"when": "abc"})
def testValidateConditionsWhenInThePast(self):
self.assertRaisesRegex(ValueError, "Cannot schedule changes in the past", self.sc_table.conditions.validate, {"when": 1})
def testValidateConditionsJustTelemetry(self):
self.sc_table.conditions.validate({"telemetry_product": "Firefox", "telemetry_channel": "nightly", "telemetry_uptake": "200000"})
def testValidateConditionsNotAllowedWhenAndOther(self):
self.assertRaisesRegex(
ValueError, "Invalid combination of conditions", self.sc_table.conditions.validate, {"when": "12345", "telemetry_product": "foo"}
)
def testValidateConditionsMissingTelemetryValue(self):
self.assertRaisesRegex(ValueError, "Invalid combination of conditions", self.sc_table.conditions.validate, {"telemetry_product": "foo"})
def testSelectIncludesConditionColumns(self):
row = self.sc_table.select(where=[self.sc_table.sc_id == 2])[0]
self.assertEqual(row["scheduled_by"], "bob")
self.assertEqual(row["complete"], False)
self.assertEqual(row["data_version"], 1)
self.assertEqual(row["base_fooid"], None)
self.assertEqual(row["base_foo"], "cc")
self.assertEqual(row["base_bar"], "ceecee")
self.assertEqual(row["base_data_version"], None)
self.assertEqual(row["telemetry_product"], None)
self.assertEqual(row["telemetry_channel"], None)
self.assertEqual(row["telemetry_uptake"], None)
self.assertEqual(row["when"], 567000)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertForExistingRow(self):
what = {"fooid": 3, "foo": "thing", "bar": "thing2", "data_version": 2, "when": 999000, "change_type": "update"}
self.sc_table.insert(changed_by="bob", **what)
sc_row = self.sc_table.t.select().where(self.sc_table.sc_id == 7).execute().fetchall()[0]
cond_row = self.sc_table.conditions.t.select().where(self.sc_table.conditions.sc_id == 7).execute().fetchall()[0]
self.assertEqual(sc_row.scheduled_by, "bob")
self.assertEqual(sc_row.change_type, "update")
self.assertEqual(sc_row.data_version, 1)
self.assertEqual(sc_row.base_fooid, 3)
self.assertEqual(sc_row.base_foo, "thing")
self.assertEqual(sc_row.base_bar, "thing2")
self.assertEqual(sc_row.base_data_version, 2)
self.assertEqual(cond_row.when, 999000)
self.assertEqual(cond_row.data_version, 1)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertForNewRow(self):
what = {"foo": "newthing1", "when": 888000, "change_type": "insert"}
self.sc_table.insert(changed_by="bob", **what)
sc_row = self.sc_table.t.select().where(self.sc_table.sc_id == 7).execute().fetchall()[0]
cond_row = self.sc_table.conditions.t.select().where(self.sc_table.conditions.sc_id == 7).execute().fetchall()[0]
self.assertEqual(sc_row.scheduled_by, "bob")
self.assertEqual(sc_row.change_type, "insert")
self.assertEqual(sc_row.data_version, 1)
self.assertEqual(sc_row.base_fooid, None)
self.assertEqual(sc_row.base_foo, "newthing1")
self.assertEqual(sc_row.base_bar, None)
self.assertEqual(sc_row.base_data_version, None)
self.assertEqual(cond_row.when, 888000)
self.assertEqual(cond_row.data_version, 1)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertRecordSignOffForUserHavingSingleRole(self):
what = {"fooid": 3, "foo": "signofftest", "bar": "thing2", "data_version": 2, "when": 999000, "change_type": "update"}
self.sc_table.insert(changed_by="bob", **what)
user_role_rows = self.table.scheduled_changes.signoffs.select(where={"username": "bob", "sc_id": 7})
self.assertEqual(len(user_role_rows), 1)
self.assertEqual(user_role_rows[0].get("username"), "bob")
self.assertEqual(user_role_rows[0].get("role"), "releng")
self.assertEqual(user_role_rows[0].get("sc_id"), 7)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertRecordSignOffForUserHavingMultipleRoles(self):
what = {"fooid": 3, "foo": "signofftest", "bar": "thing2", "data_version": 2, "when": 999000, "change_type": "update"}
self.sc_table.insert(changed_by="mary", **what)
user_role_rows = self.table.scheduled_changes.signoffs.select(where={"username": "mary", "sc_id": 7})
self.assertEqual(len(user_role_rows), 1)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertRecordSignOffUnneededRole(self):
what = {"fooid": 3, "foo": "signofftest", "bar": "thing2", "data_version": 2, "when": 999000, "change_type": "update"}
self.sc_table.insert(changed_by="jane", **what)
user_role_rows = self.table.scheduled_changes.signoffs.select(where={"username": "jane", "sc_id": 7})
self.assertEqual(len(user_role_rows), 0)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertWithNonAutoincrement(self):
class TestTable2(AUSTable):
def __init__(self, db, metadata):
self.table = Table(
"test_table2", metadata, Column("foo_name", String(15), primary_key=True), Column("foo", String(15)), Column("bar", String(15))
)
super(TestTable2, self).__init__(db, "sqlite", scheduled_changes=True, versioned=True)
def getPotentialRequiredSignoffs(self, *args, **kwargs):
return None
table = TestTable2(self.db, self.metadata)
self.metadata.create_all()
what = {"foo_name": "i'm a foo", "foo": "123", "bar": "456", "when": 876000, "change_type": "insert"}
table.scheduled_changes.insert(changed_by="mary", **what)
sc_row = table.scheduled_changes.t.select().where(table.scheduled_changes.sc_id == 1).execute().fetchall()[0]
cond_row = table.scheduled_changes.conditions.t.select().where(table.scheduled_changes.conditions.sc_id == 1).execute().fetchall()[0]
self.assertEqual(sc_row.scheduled_by, "mary")
self.assertEqual(sc_row.change_type, "insert")
self.assertEqual(sc_row.data_version, 1)
self.assertEqual(sc_row.base_foo_name, "i'm a foo")
self.assertEqual(sc_row.base_foo, "123")
self.assertEqual(sc_row.base_bar, "456")
self.assertEqual(sc_row.base_data_version, None)
self.assertEqual(cond_row.when, 876000)
self.assertEqual(cond_row.data_version, 1)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertWithNonNullablePKColumn(self):
class TestTable(AUSTable):
def __init__(self, db, metadata):
self.table = Table(
"test_table_null_pk",
metadata,
Column("foo_id", Integer, primary_key=True),
Column("bar", String(15), primary_key=True, nullable=False),
Column("baz", String(15)),
)
super(TestTable, self).__init__(db, "sqlite", scheduled_changes=True, historyClass=None, versioned=True)
table = TestTable(self.db, self.metadata)
self.metadata.create_all()
table_sc = table.scheduled_changes
what = {"baz": "baz", "change_type": "insert", "when": 876000}
self.assertRaisesRegex(ValueError, "Missing primary key column ", table_sc.insert, changed_by="alice", **what)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertForExistingNoSuchRow(self):
what = {"fooid": 10, "foo": "thing", "data_version": 1, "when": 999000, "change_type": "update"}
self.assertRaisesRegex(
ValueError, "Cannot create scheduled change with data_version for non-existent row", self.sc_table.insert, changed_by="bob", **what
)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertMissingRequiredPartOfPK(self):
class TestTable2(AUSTable):
def __init__(self, db, metadata):
self.table = Table(
"test_table2", metadata, Column("fooid", Integer, primary_key=True), Column("foo", String(15), primary_key=True), Column("bar", String(15))
)
super(TestTable2, self).__init__(db, "sqlite", scheduled_changes=True, versioned=True)
def getPotentialRequiredSignoffs(self, *args, **kwargs):
return None
table = TestTable2("fake", self.metadata)
self.metadata.create_all()
what = {"fooid": 2, "when": 4532000, "change_type": "insert"}
self.assertRaisesRegex(ValueError, "Missing primary key column", table.scheduled_changes.insert, changed_by="bob", **what)
def testInsertWithMalformedTimestamp(self):
what = {"foo": "blah", "when": "abc", "change_type": "insert"}
self.assertRaisesRegex(ValueError, "Cannot parse", self.sc_table.insert, changed_by="bob", **what)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertDataVersionChanged(self):
"""Tests to make sure a scheduled change update is rejected if data
version changes between grabbing the row to create a change, and
submitting the scheduled change."""
self.table.update([self.table.fooid == 3], what={"foo": "bb"}, changed_by="bob", old_data_version=2)
what = {"fooid": 3, "data_version": 2, "bar": "blah", "when": 456000, "change_type": "update"}
self.assertRaises(OutdatedDataError, self.sc_table.insert, changed_by="bob", **what)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertWithoutPermissionOnBaseTable(self):
what = {"fooid": 5, "bar": "blah", "when": 343000, "change_type": "insert"}
self.assertRaises(PermissionDeniedError, self.sc_table.insert, changed_by="nancy", **what)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertWithoutPermissionOnBaseTableForUpdate(self):
what = {"fooid": 3, "bar": "blah", "when": 343000, "data_version": 2, "change_type": "update"}
self.assertRaises(PermissionDeniedError, self.sc_table.insert, changed_by="nancy", **what)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertRejectedWithAlreadyScheduledChange(self):
what = {"fooid": 2, "foo": "b", "bar": "thing2", "data_version": 2, "when": 929000, "change_type": "update"}
self.assertRaises(ChangeScheduledError, self.sc_table.insert, changed_by="bob", **what)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertRaisesErrorOnDataVersionBetweenCoreAndConditions(self):
# We need to fake out the conditions table insert so we do it ourselves
def noop(*args, **kwargs):
pass
self.sc_table.conditions.insert = noop
self.sc_table.conditions.t.insert().execute(sc_id=7, when=10000000, data_version=4)
what = {"foo": "newthing1", "when": 888000, "change_type": "insert"}
self.assertRaises(MismatchedDataVersionError, self.sc_table.insert, changed_by="bob", **what)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testInsertCreateExistingPK(self):
what = {"fooid": 3, "foo": "mine is better", "when": 99999999, "change_type": "insert"}
self.assertRaisesRegex(ValueError, "Cannot schedule change for duplicate PK", self.sc_table.insert, changed_by="bob", **what)
@mock.patch("time.time", mock.MagicMock(return_value=200))
def testDeleteScheduledChangeWithoutPKColumns(self):
class TestTable2(AUSTable):
def __init__(self, db, metadata):
self.table = Table(
"test_table2", metadata, Column("fooid", Integer, primary_key=True), Column("foo", String(15), primary_key=True), Column("bar", String(15))
)
super(TestTable2, self).__init__(db, "sqlite", scheduled_changes=True, versioned=True)