-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathdb_test_base.py
More file actions
3465 lines (3108 loc) · 148 KB
/
db_test_base.py
File metadata and controls
3465 lines (3108 loc) · 148 KB
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 (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
# This module is free software, and you may redistribute it and/or modify
# under the same terms as Python, so long as this copyright message and
# disclaimer are retained in their original form.
#
# IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
# DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
# BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
# SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
from __future__ import print_function
import unittest, os, shutil, errno, imp, sys, time, pprint, base64, os.path
import logging, cgi
from . import gpgmelib
from email import message_from_string
import pytest
from roundup.hyperdb import String, Password, Link, Multilink, Date, \
Interval, DatabaseError, Boolean, Number, Node, Integer
from roundup.mailer import Mailer
from roundup import date, password, init, instance, configuration, \
roundupdb, i18n, hyperdb
from roundup.cgi.templating import HTMLItem
from roundup.cgi.templating import HTMLProperty, _HTMLItem, anti_csrf_nonce
from roundup.cgi import client, actions
from roundup.cgi.engine_zopetal import RoundupPageTemplate
from roundup.cgi.templating import HTMLItem
from roundup.exceptions import UsageError, Reject
from roundup.anypy.strings import b2s, s2b, u2s
from roundup.anypy.cmp_ import NoneAndDictComparable
from roundup.anypy.email_ import message_from_bytes
from .mocknull import MockNull
config = configuration.CoreConfig()
config.DATABASE = "db"
config.RDBMS_NAME = "rounduptest"
config.RDBMS_HOST = "localhost"
config.RDBMS_USER = "rounduptest"
config.RDBMS_PASSWORD = "rounduptest"
config.RDBMS_TEMPLATE = "template0"
# these TRACKER_WEB and MAIL_DOMAIN values are used in mailgw tests
config.MAIL_DOMAIN = "your.tracker.email.domain.example"
config.TRACKER_WEB = "http://tracker.example/cgi-bin/roundup.cgi/bugs/"
# uncomment the following to have excessive debug output from test cases
# FIXME: tracker logging level should be increased by -v arguments
# to 'run_tests.py' script
#config.LOGGING_FILENAME = "/tmp/logfile"
#config.LOGGING_LEVEL = "DEBUG"
config.init_logging()
def setupTracker(dirname, backend="anydbm"):
"""Install and initialize new tracker in dirname; return tracker instance.
If the directory exists, it is wiped out before the operation.
"""
global config
try:
shutil.rmtree(dirname)
except OSError as error:
if error.errno not in (errno.ENOENT, errno.ESRCH): raise
# create the instance
init.install(dirname, os.path.join(os.path.dirname(__file__),
'..',
'share',
'roundup',
'templates',
'classic'))
config.RDBMS_BACKEND = backend
config.save(os.path.join(dirname, 'config.ini'))
tracker = instance.open(dirname)
if tracker.exists():
tracker.nuke()
tracker.init(password.Password('sekrit'))
return tracker
def setupSchema(db, create, module):
mls = module.Class(db, "mls", name=String())
mls.setkey("name")
status = module.Class(db, "status", name=String(), mls=Multilink("mls"))
status.setkey("name")
priority = module.Class(db, "priority", name=String(), order=String())
priority.setkey("name")
user = module.Class(db, "user", username=String(),
password=Password(quiet=True), assignable=Boolean(quiet=True),
age=Number(quiet=True), roles=String(), address=String(),
rating=Integer(quiet=True), supervisor=Link('user'),
realname=String(quiet=True), longnumber=Number(use_double=True))
user.setkey("username")
file = module.FileClass(db, "file", name=String(), type=String(),
comment=String(indexme="yes"), fooz=Password())
file_nidx = module.FileClass(db, "file_nidx", content=String(indexme='no'))
# initialize quiet mode a second way without using Multilink("user", quiet=True)
mynosy = Multilink("user")
mynosy.quiet = True
issue = module.IssueClass(db, "issue", title=String(indexme="yes"),
status=Link("status"), nosy=mynosy, deadline=Date(quiet=True),
foo=Interval(quiet=True, default_value=date.Interval('-1w')),
files=Multilink("file"), assignedto=Link('user', quiet=True),
priority=Link('priority'), spam=Multilink('msg'), feedback=Link('msg'))
stuff = module.Class(db, "stuff", stuff=String())
session = module.Class(db, 'session', title=String())
msg = module.FileClass(db, "msg", date=Date(),
author=Link("user", do_journal='no'), files=Multilink('file'),
inreplyto=String(), messageid=String(),
recipients=Multilink("user", do_journal='no'))
session.disableJournalling()
db.post_init()
if create:
user.create(username="admin", roles='Admin',
password=password.Password('sekrit'))
user.create(username="fred", roles='User',
password=password.Password('sekrit'), address='fred@example.com')
u1 = mls.create(name="unread_1")
u2 = mls.create(name="unread_2")
status.create(name="unread",mls=[u1, u2])
status.create(name="in-progress")
status.create(name="testing")
status.create(name="resolved")
priority.create(name="feature", order="2")
priority.create(name="wish", order="3")
priority.create(name="bug", order="1")
db.commit()
# nosy tests require this
db.security.addPermissionToRole('User', 'View', 'msg')
# quiet journal tests require this
# QuietJournal - reference used later in tests
v1 = db.security.addPermission(name='View', klass='user',
properties=['username', 'supervisor', 'assignable'],
description="Prevent users from seeing roles")
db.security.addPermissionToRole("User", v1)
class MyTestCase(object):
def tearDown(self):
if hasattr(self, 'db'):
self.db.close()
if os.path.exists(config.DATABASE):
shutil.rmtree(config.DATABASE)
def open_database(self, user='admin'):
self.db = self.module.Database(config, user)
if 'LOGGING_LEVEL' in os.environ:
logger = logging.getLogger('roundup.hyperdb')
logger.setLevel(os.environ['LOGGING_LEVEL'])
class commonDBTest(MyTestCase):
def setUp(self):
# remove previous test, ignore errors
if os.path.exists(config.DATABASE):
shutil.rmtree(config.DATABASE)
os.makedirs(config.DATABASE + '/files')
self.open_database()
setupSchema(self.db, 1, self.module)
def iterSetup(self, classname='issue'):
cls = getattr(self.db, classname)
def filt_iter(*args, **kw):
""" for checking equivalence of filter and filter_iter """
return list(cls.filter_iter(*args, **kw))
return self.assertEqual, cls.filter, filt_iter
def filteringSetupTransitiveSearch(self, classname='issue'):
u_m = {}
k = 30
for user in (
{'username': 'ceo', 'age': 129},
{'username': 'grouplead1', 'age': 29, 'supervisor': '3'},
{'username': 'grouplead2', 'age': 29, 'supervisor': '3'},
{'username': 'worker1', 'age': 25, 'supervisor' : '4'},
{'username': 'worker2', 'age': 24, 'supervisor' : '4'},
{'username': 'worker3', 'age': 23, 'supervisor' : '5'},
{'username': 'worker4', 'age': 22, 'supervisor' : '5'},
{'username': 'worker5', 'age': 21, 'supervisor' : '5'}):
u = self.db.user.create(**user)
u_m [u] = self.db.msg.create(author = u, content = ' '
, date = date.Date ('2006-01-%s' % k))
k -= 1
i = date.Interval('-1d')
for issue in (
{'title': 'ts1', 'status': '2', 'assignedto': '6',
'priority': '3', 'messages' : [u_m ['6']], 'nosy' : ['4']},
{'title': 'ts2', 'status': '1', 'assignedto': '6',
'priority': '3', 'messages' : [u_m ['6']], 'nosy' : ['5']},
{'title': 'ts4', 'status': '2', 'assignedto': '7',
'priority': '3', 'messages' : [u_m ['7']]},
{'title': 'ts5', 'status': '1', 'assignedto': '8',
'priority': '3', 'messages' : [u_m ['8']]},
{'title': 'ts6', 'status': '2', 'assignedto': '9',
'priority': '3', 'messages' : [u_m ['9']]},
{'title': 'ts7', 'status': '1', 'assignedto': '10',
'priority': '3', 'messages' : [u_m ['10']]},
{'title': 'ts8', 'status': '2', 'assignedto': '10',
'priority': '3', 'messages' : [u_m ['10']], 'foo' : i},
{'title': 'ts9', 'status': '1', 'assignedto': '10',
'priority': '3', 'messages' : [u_m ['10'], u_m ['9']]}):
self.db.issue.create(**issue)
return self.iterSetup(classname)
class DBTest(commonDBTest):
def testRefresh(self):
self.db.refresh_database()
#
# automatic properties (well, the two easy ones anyway)
#
def testCreatorProperty(self):
i = self.db.issue
id1 = i.create(title='spam')
self.db.journaltag = 'fred'
id2 = i.create(title='spam')
self.assertNotEqual(id1, id2)
self.assertNotEqual(i.get(id1, 'creator'), i.get(id2, 'creator'))
def testActorProperty(self):
i = self.db.issue
id1 = i.create(title='spam')
self.db.journaltag = 'fred'
i.set(id1, title='asfasd')
self.assertNotEqual(i.get(id1, 'creator'), i.get(id1, 'actor'))
# ID number controls
def testIDGeneration(self):
id1 = self.db.issue.create(title="spam", status='1')
id2 = self.db.issue.create(title="eggs", status='2')
self.assertNotEqual(id1, id2)
def testIDSetting(self):
# XXX numeric ids
self.db.setid('issue', 10)
id2 = self.db.issue.create(title="eggs", status='2')
self.assertEqual('11', id2)
#
# basic operations
#
def testEmptySet(self):
id1 = self.db.issue.create(title="spam", status='1')
self.db.issue.set(id1)
# String
def testStringChange(self):
for commit in (0,1):
# test set & retrieve
nid = self.db.issue.create(title="spam", status='1')
self.assertEqual(self.db.issue.get(nid, 'title'), 'spam')
# change and make sure we retrieve the correct value
self.db.issue.set(nid, title='eggs')
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, 'title'), 'eggs')
def testStringUnset(self):
for commit in (0,1):
nid = self.db.issue.create(title="spam", status='1')
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, 'title'), 'spam')
# make sure we can unset
self.db.issue.set(nid, title=None)
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "title"), None)
# FileClass "content" property (no unset test)
def testFileClassContentChange(self):
for commit in (0,1):
# test set & retrieve
nid = self.db.file.create(content="spam")
self.assertEqual(self.db.file.get(nid, 'content'), 'spam')
# change and make sure we retrieve the correct value
self.db.file.set(nid, content='eggs')
if commit: self.db.commit()
self.assertEqual(self.db.file.get(nid, 'content'), 'eggs')
def testStringUnicode(self):
# test set & retrieve
ustr = u2s(u'\xe4\xf6\xfc\u20ac')
nid = self.db.issue.create(title=ustr, status='1')
self.assertEqual(self.db.issue.get(nid, 'title'), ustr)
# change and make sure we retrieve the correct value
ustr2 = u2s(u'change \u20ac change')
self.db.issue.set(nid, title=ustr2)
self.db.commit()
self.assertEqual(self.db.issue.get(nid, 'title'), ustr2)
# test set & retrieve (this time for file contents)
nid = self.db.file.create(content=ustr)
self.assertEqual(self.db.file.get(nid, 'content'), ustr)
self.assertEqual(self.db.file.get(nid, 'binary_content'), s2b(ustr))
def testStringBinary(self):
''' Create file with binary content that is not able
to be interpreted as unicode. Try to cause file module
trigger and handle UnicodeDecodeError
and get valid output
'''
# test set & retrieve
bstr = b'\x00\xF0\x34\x33' # random binary data
# test set & retrieve (this time for file contents)
nid = self.db.file.create(content=bstr)
print(nid)
print(repr(self.db.file.get(nid, 'content')))
print(repr(self.db.file.get(nid, 'binary_content')))
p3val='file1 is not text, retrieve using binary_content property. mdsum: 0e1d1b47e4bd1beab3afc9b79f596c1d'
if sys.version_info[0] > 2:
# python 3
self.assertEqual(self.db.file.get(nid, 'content'), p3val)
self.assertEqual(self.db.file.get(nid, 'binary_content'),
bstr)
else:
# python 2
self.assertEqual(self.db.file.get(nid, 'content'), bstr)
self.assertEqual(self.db.file.get(nid, 'binary_content'), bstr)
# Link
def testLinkChange(self):
self.assertRaises(IndexError, self.db.issue.create, title="spam",
status='100')
for commit in (0,1):
nid = self.db.issue.create(title="spam", status='1')
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "status"), '1')
self.db.issue.set(nid, status='2')
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "status"), '2')
def testLinkUnset(self):
for commit in (0,1):
nid = self.db.issue.create(title="spam", status='1')
if commit: self.db.commit()
self.db.issue.set(nid, status=None)
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "status"), None)
# Multilink
def testMultilinkChange(self):
for commit in (0,1):
self.assertRaises(IndexError, self.db.issue.create, title="spam",
nosy=['foo%s'%commit])
u1 = self.db.user.create(username='foo%s'%commit)
u2 = self.db.user.create(username='bar%s'%commit)
nid = self.db.issue.create(title="spam", nosy=[u1])
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "nosy"), [u1])
self.db.issue.set(nid, nosy=[])
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "nosy"), [])
self.db.issue.set(nid, nosy=[u1,u2])
if commit: self.db.commit()
l = [u1,u2]; l.sort()
m = self.db.issue.get(nid, "nosy"); m.sort()
self.assertEqual(l, m)
# verify that when we pass None to an Multilink it sets
# it to an empty list
self.db.issue.set(nid, nosy=None)
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "nosy"), [])
def testMakeSeveralMultilinkedNodes(self):
for commit in (0,1):
u1 = self.db.user.create(username='foo%s'%commit)
u2 = self.db.user.create(username='bar%s'%commit)
u3 = self.db.user.create(username='baz%s'%commit)
nid = self.db.issue.create(title="spam", nosy=[u1])
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "nosy"), [u1])
self.db.issue.set(nid, deadline=date.Date('.'))
self.db.issue.set(nid, nosy=[u1,u2], title='ta%s'%commit)
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "nosy"), [u1,u2])
self.db.issue.set(nid, deadline=date.Date('.'))
self.db.issue.set(nid, nosy=[u1,u2,u3], title='tb%s'%commit)
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "nosy"), [u1,u2,u3])
def testMultilinkChangeIterable(self):
for commit in (0,1):
# invalid nosy value assertion
self.assertRaises(IndexError, self.db.issue.create, title='spam',
nosy=['foo%s'%commit])
# invalid type for nosy create
self.assertRaises(TypeError, self.db.issue.create, title='spam',
nosy=1)
u1 = self.db.user.create(username='foo%s'%commit)
u2 = self.db.user.create(username='bar%s'%commit)
# try a couple of the built-in iterable types to make
# sure that we accept them and handle them properly
# try a set as input for the multilink
nid = self.db.issue.create(title="spam", nosy=set(u1))
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "nosy"), [u1])
self.assertRaises(TypeError, self.db.issue.set, nid,
nosy='invalid type')
# test with a tuple
self.db.issue.set(nid, nosy=tuple())
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "nosy"), [])
# make sure we accept a frozen set
self.db.issue.set(nid, nosy=set([u1,u2]))
if commit: self.db.commit()
l = [u1,u2]; l.sort()
m = self.db.issue.get(nid, "nosy"); m.sort()
self.assertEqual(l, m)
# XXX one day, maybe...
# def testMultilinkOrdering(self):
# for i in range(10):
# self.db.user.create(username='foo%s'%i)
# i = self.db.issue.create(title="spam", nosy=['5','3','12','4'])
# self.db.commit()
# l = self.db.issue.get(i, "nosy")
# # all backends should return the Multilink numeric-id-sorted
# self.assertEqual(l, ['3', '4', '5', '12'])
# Date
def testDateChange(self):
self.assertRaises(TypeError, self.db.issue.create,
title='spam', deadline=1)
for commit in (0,1):
nid = self.db.issue.create(title="spam", status='1')
self.assertRaises(TypeError, self.db.issue.set, nid, deadline=1)
a = self.db.issue.get(nid, "deadline")
if commit: self.db.commit()
self.db.issue.set(nid, deadline=date.Date())
b = self.db.issue.get(nid, "deadline")
if commit: self.db.commit()
self.assertNotEqual(a, b)
self.assertNotEqual(b, date.Date('1970-1-1.00:00:00'))
# The 1970 date will fail for metakit -- it is used
# internally for storing NULL. The others would, too
# because metakit tries to convert date.timestamp to an int
# for storing and fails with an overflow.
for d in [date.Date (x) for x in ('2038', '1970', '0033', '9999')]:
self.db.issue.set(nid, deadline=d)
if commit: self.db.commit()
c = self.db.issue.get(nid, "deadline")
self.assertEqual(c, d)
def testDateLeapYear(self):
nid = self.db.issue.create(title='spam', status='1',
deadline=date.Date('2008-02-29'))
self.assertEqual(str(self.db.issue.get(nid, 'deadline')),
'2008-02-29.00:00:00')
self.assertEqual(self.db.issue.filter(None,
{'deadline': '2008-02-29'}), [nid])
self.assertEqual(list(self.db.issue.filter_iter(None,
{'deadline': '2008-02-29'})), [nid])
self.db.issue.set(nid, deadline=date.Date('2008-03-01'))
self.assertEqual(str(self.db.issue.get(nid, 'deadline')),
'2008-03-01.00:00:00')
self.assertEqual(self.db.issue.filter(None,
{'deadline': '2008-02-29'}), [])
self.assertEqual(list(self.db.issue.filter_iter(None,
{'deadline': '2008-02-29'})), [])
def testDateUnset(self):
for commit in (0,1):
nid = self.db.issue.create(title="spam", status='1')
self.db.issue.set(nid, deadline=date.Date())
if commit: self.db.commit()
self.assertNotEqual(self.db.issue.get(nid, "deadline"), None)
self.db.issue.set(nid, deadline=None)
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "deadline"), None)
def testDateSort(self):
d1 = date.Date('.')
ae, filter, filter_iter = self.filteringSetup()
nid = self.db.issue.create(title="nodeadline", status='1')
self.db.commit()
for filt in filter, filter_iter:
ae(filt(None, {}, ('+','deadline')), ['5', '2', '1', '3', '4'])
ae(filt(None, {}, ('+','id'), ('+', 'deadline')),
['5', '2', '1', '3', '4'])
ae(filt(None, {}, ('-','id'), ('-', 'deadline')),
['4', '3', '1', '2', '5'])
def testDateSortMultilink(self):
d1 = date.Date('.')
ae, filter, filter_iter = self.filteringSetup()
nid = self.db.issue.create(title="nodeadline", status='1')
self.db.commit()
ae(sorted(self.db.issue.get('1','nosy')), [])
ae(sorted(self.db.issue.get('2','nosy')), [])
ae(sorted(self.db.issue.get('3','nosy')), ['1','2'])
ae(sorted(self.db.issue.get('4','nosy')), ['1','2','3'])
ae(sorted(self.db.issue.get('5','nosy')), [])
ae(self.db.user.get('1','username'), 'admin')
ae(self.db.user.get('2','username'), 'fred')
ae(self.db.user.get('3','username'), 'bleep')
# filter_iter currently doesn't work for Multilink sort
# so testing only filter
ae(filter(None, {}, ('+', 'id'), ('+','nosy')),
['1', '2', '5', '4', '3'])
ae(filter(None, {}, ('+','deadline'), ('+', 'nosy')),
['5', '2', '1', '4', '3'])
ae(filter(None, {}, ('+','nosy'), ('+', 'deadline')),
['5', '2', '1', '3', '4'])
# Interval
def testIntervalChange(self):
self.assertRaises(TypeError, self.db.issue.create,
title='spam', foo=1)
for commit in (0,1):
nid = self.db.issue.create(title="spam", status='1')
self.assertRaises(TypeError, self.db.issue.set, nid, foo=1)
if commit: self.db.commit()
a = self.db.issue.get(nid, "foo")
i = date.Interval('-1d')
self.db.issue.set(nid, foo=i)
if commit: self.db.commit()
self.assertNotEqual(self.db.issue.get(nid, "foo"), a)
self.assertEqual(i, self.db.issue.get(nid, "foo"))
j = date.Interval('1y')
self.db.issue.set(nid, foo=j)
if commit: self.db.commit()
self.assertNotEqual(self.db.issue.get(nid, "foo"), i)
self.assertEqual(j, self.db.issue.get(nid, "foo"))
def testIntervalUnset(self):
for commit in (0,1):
nid = self.db.issue.create(title="spam", status='1')
self.db.issue.set(nid, foo=date.Interval('-1d'))
if commit: self.db.commit()
self.assertNotEqual(self.db.issue.get(nid, "foo"), None)
self.db.issue.set(nid, foo=None)
if commit: self.db.commit()
self.assertEqual(self.db.issue.get(nid, "foo"), None)
# Boolean
def testBooleanSet(self):
nid = self.db.user.create(username='one', assignable=1)
self.assertEqual(self.db.user.get(nid, "assignable"), 1)
nid = self.db.user.create(username='two', assignable=0)
self.assertEqual(self.db.user.get(nid, "assignable"), 0)
def testBooleanChange(self):
userid = self.db.user.create(username='foo', assignable=1)
self.assertEqual(1, self.db.user.get(userid, 'assignable'))
self.db.user.set(userid, assignable=0)
self.assertEqual(self.db.user.get(userid, 'assignable'), 0)
self.db.user.set(userid, assignable=1)
self.assertEqual(self.db.user.get(userid, 'assignable'), 1)
def testBooleanUnset(self):
nid = self.db.user.create(username='foo', assignable=1)
self.db.user.set(nid, assignable=None)
self.assertEqual(self.db.user.get(nid, "assignable"), None)
# Number
def testNumberChange(self):
nid = self.db.user.create(username='foo', age=1)
self.assertEqual(1, self.db.user.get(nid, 'age'))
self.db.user.set(nid, age=3)
self.assertNotEqual(self.db.user.get(nid, 'age'), 1)
self.db.user.set(nid, age=1.0)
self.assertEqual(self.db.user.get(nid, 'age'), 1)
self.db.user.set(nid, age=0)
self.assertEqual(self.db.user.get(nid, 'age'), 0)
nid = self.db.user.create(username='bar', age=0)
self.assertEqual(self.db.user.get(nid, 'age'), 0)
def testNumberUnset(self):
nid = self.db.user.create(username='foo', age=1)
self.db.user.set(nid, age=None)
self.assertEqual(self.db.user.get(nid, "age"), None)
# Long number
def testDoubleChange(self):
lnl = 100.12345678
ln = 100.123456789
lng = 100.12345679
nid = self.db.user.create(username='foo', longnumber=ln)
self.assertEqual(self.db.user.get(nid, 'longnumber') < lng, True)
self.assertEqual(self.db.user.get(nid, 'longnumber') > lnl, True)
lnl = 1.0012345678e55
ln = 1.00123456789e55
lng = 1.0012345679e55
self.db.user.set(nid, longnumber=ln)
self.assertEqual(self.db.user.get(nid, 'longnumber') < lng, True)
self.assertEqual(self.db.user.get(nid, 'longnumber') > lnl, True)
self.db.user.set(nid, longnumber=-1)
self.assertEqual(self.db.user.get(nid, 'longnumber'), -1)
self.db.user.set(nid, longnumber=0)
self.assertEqual(self.db.user.get(nid, 'longnumber'), 0)
nid = self.db.user.create(username='bar', longnumber=0)
self.assertEqual(self.db.user.get(nid, 'longnumber'), 0)
def testDoubleUnset(self):
nid = self.db.user.create(username='foo', longnumber=1.2345)
self.db.user.set(nid, longnumber=None)
self.assertEqual(self.db.user.get(nid, "longnumber"), None)
# Integer
def testIntegerChange(self):
nid = self.db.user.create(username='foo', rating=100)
self.assertEqual(100, self.db.user.get(nid, 'rating'))
self.db.user.set(nid, rating=300)
self.assertNotEqual(self.db.user.get(nid, 'rating'), 100)
self.db.user.set(nid, rating=-1)
self.assertEqual(self.db.user.get(nid, 'rating'), -1)
self.db.user.set(nid, rating=0)
self.assertEqual(self.db.user.get(nid, 'rating'), 0)
nid = self.db.user.create(username='bar', rating=0)
self.assertEqual(self.db.user.get(nid, 'rating'), 0)
def testIntegerUnset(self):
nid = self.db.user.create(username='foo', rating=1)
self.db.user.set(nid, rating=None)
self.assertEqual(self.db.user.get(nid, "rating"), None)
# Password
def testPasswordChange(self):
x = password.Password('x')
userid = self.db.user.create(username='foo', password=x)
self.assertEqual(x, self.db.user.get(userid, 'password'))
self.assertEqual(self.db.user.get(userid, 'password'), 'x')
y = password.Password('y')
self.db.user.set(userid, password=y)
self.assertEqual(self.db.user.get(userid, 'password'), 'y')
self.assertRaises(TypeError, self.db.user.create, userid,
username='bar', password='x')
self.assertRaises(TypeError, self.db.user.set, userid, password='x')
def testPasswordUnset(self):
x = password.Password('x')
nid = self.db.user.create(username='foo', password=x)
self.db.user.set(nid, assignable=None)
self.assertEqual(self.db.user.get(nid, "assignable"), None)
# key value
def testKeyValue(self):
self.assertRaises(ValueError, self.db.user.create)
newid = self.db.user.create(username="spam")
self.assertEqual(self.db.user.lookup('spam'), newid)
self.db.commit()
self.assertEqual(self.db.user.lookup('spam'), newid)
self.db.user.retire(newid)
self.assertRaises(KeyError, self.db.user.lookup, 'spam')
# use the key again now that the old is retired
newid2 = self.db.user.create(username="spam")
self.assertNotEqual(newid, newid2)
# try to restore old node. this shouldn't succeed!
self.assertRaises(KeyError, self.db.user.restore, newid)
self.assertRaises(TypeError, self.db.issue.lookup, 'fubar')
# label property
def testLabelProp(self):
# key prop
self.assertEqual(self.db.status.labelprop(), 'name')
self.assertEqual(self.db.user.labelprop(), 'username')
# title
self.assertEqual(self.db.issue.labelprop(), 'title')
# name
self.assertEqual(self.db.file.labelprop(), 'name')
# id
self.assertEqual(self.db.stuff.labelprop(default_to_id=1), 'id')
# retirement
def testRetire(self):
self.db.issue.create(title="spam", status='1')
b = self.db.status.get('1', 'name')
a = self.db.status.list()
nodeids = self.db.status.getnodeids()
self.db.status.retire('1')
others = nodeids[:]
others.remove('1')
self.assertEqual(set(self.db.status.getnodeids()),
set(nodeids))
self.assertEqual(set(self.db.status.getnodeids(retired=True)),
set(['1']))
self.assertEqual(set(self.db.status.getnodeids(retired=False)),
set(others))
self.assertTrue(self.db.status.is_retired('1'))
# make sure the list is different
self.assertNotEqual(a, self.db.status.list())
# can still access the node if necessary
self.assertEqual(self.db.status.get('1', 'name'), b)
self.assertRaises(IndexError, self.db.status.set, '1', name='hello')
self.db.commit()
self.assertTrue(self.db.status.is_retired('1'))
self.assertEqual(self.db.status.get('1', 'name'), b)
self.assertNotEqual(a, self.db.status.list())
# try to restore retired node
self.db.status.restore('1')
self.assertTrue(not self.db.status.is_retired('1'))
def testCacheCreateSet(self):
self.db.issue.create(title="spam", status='1')
a = self.db.issue.get('1', 'title')
self.assertEqual(a, 'spam')
self.db.issue.set('1', title='ham')
b = self.db.issue.get('1', 'title')
self.assertEqual(b, 'ham')
def testSerialisation(self):
nid = self.db.issue.create(title="spam", status='1',
deadline=date.Date(), foo=date.Interval('-1d'))
self.db.commit()
assert isinstance(self.db.issue.get(nid, 'deadline'), date.Date)
assert isinstance(self.db.issue.get(nid, 'foo'), date.Interval)
uid = self.db.user.create(username="fozzy",
password=password.Password('t. bear'))
self.db.commit()
assert isinstance(self.db.user.get(uid, 'password'), password.Password)
def testTransactions(self):
# remember the number of items we started
num_issues = len(self.db.issue.list())
num_files = self.db.numfiles()
self.db.issue.create(title="don't commit me!", status='1')
self.assertNotEqual(num_issues, len(self.db.issue.list()))
self.db.rollback()
self.assertEqual(num_issues, len(self.db.issue.list()))
self.db.issue.create(title="please commit me!", status='1')
self.assertNotEqual(num_issues, len(self.db.issue.list()))
self.db.commit()
self.assertNotEqual(num_issues, len(self.db.issue.list()))
self.db.rollback()
self.assertNotEqual(num_issues, len(self.db.issue.list()))
self.db.file.create(name="test", type="text/plain", content="hi")
self.db.rollback()
self.assertEqual(num_files, self.db.numfiles())
for i in range(10):
self.db.file.create(name="test", type="text/plain",
content="hi %d"%(i))
self.db.commit()
num_files2 = self.db.numfiles()
self.assertNotEqual(num_files, num_files2)
self.db.file.create(name="test", type="text/plain", content="hi")
self.db.rollback()
self.assertNotEqual(num_files, self.db.numfiles())
self.assertEqual(num_files2, self.db.numfiles())
# rollback / cache interaction
name1 = self.db.user.get('1', 'username')
self.db.user.set('1', username = name1+name1)
# get the prop so the info's forced into the cache (if there is one)
self.db.user.get('1', 'username')
self.db.rollback()
name2 = self.db.user.get('1', 'username')
self.assertEqual(name1, name2)
def testDestroyBlob(self):
# destroy an uncommitted blob
f1 = self.db.file.create(content='hello', type="text/plain")
self.db.commit()
fn = self.db.filename('file', f1)
self.db.file.destroy(f1)
self.db.commit()
self.assertEqual(os.path.exists(fn), False)
def testDestroyNoJournalling(self):
self.innerTestDestroy(klass=self.db.session)
def testDestroyJournalling(self):
self.innerTestDestroy(klass=self.db.issue)
def innerTestDestroy(self, klass):
newid = klass.create(title='Mr Friendly')
n = len(klass.list())
self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
count = klass.count()
klass.destroy(newid)
self.assertNotEqual(count, klass.count())
self.assertRaises(IndexError, klass.get, newid, 'title')
self.assertNotEqual(len(klass.list()), n)
if klass.do_journal:
self.assertRaises(IndexError, klass.history, newid)
# now with a commit
newid = klass.create(title='Mr Friendly')
n = len(klass.list())
self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
self.db.commit()
count = klass.count()
klass.destroy(newid)
self.assertNotEqual(count, klass.count())
self.assertRaises(IndexError, klass.get, newid, 'title')
self.db.commit()
self.assertRaises(IndexError, klass.get, newid, 'title')
self.assertNotEqual(len(klass.list()), n)
if klass.do_journal:
self.assertRaises(IndexError, klass.history, newid)
# now with a rollback
newid = klass.create(title='Mr Friendly')
n = len(klass.list())
self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
self.db.commit()
count = klass.count()
klass.destroy(newid)
self.assertNotEqual(len(klass.list()), n)
self.assertRaises(IndexError, klass.get, newid, 'title')
self.db.rollback()
self.assertEqual(count, klass.count())
self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
self.assertEqual(len(klass.list()), n)
if klass.do_journal:
self.assertNotEqual(klass.history(newid), [])
def testExceptions(self):
# this tests the exceptions that should be raised
ar = self.assertRaises
ar(KeyError, self.db.getclass, 'fubar')
#
# class create
#
# string property
ar(TypeError, self.db.status.create, name=1)
# id, creation, creator and activity properties are reserved
ar(KeyError, self.db.status.create, id=1)
ar(KeyError, self.db.status.create, creation=1)
ar(KeyError, self.db.status.create, creator=1)
ar(KeyError, self.db.status.create, activity=1)
ar(KeyError, self.db.status.create, actor=1)
# invalid property name
ar(KeyError, self.db.status.create, foo='foo')
# key name clash
ar(ValueError, self.db.status.create, name='unread')
# invalid link index
ar(IndexError, self.db.issue.create, title='foo', status='bar')
# invalid link value
ar(ValueError, self.db.issue.create, title='foo', status=1)
# invalid multilink type
ar(TypeError, self.db.issue.create, title='foo', status='1',
nosy='hello')
# invalid multilink index type
ar(ValueError, self.db.issue.create, title='foo', status='1',
nosy=[1])
# invalid multilink index
ar(IndexError, self.db.issue.create, title='foo', status='1',
nosy=['10'])
#
# key property
#
# key must be a String
ar(TypeError, self.db.file.setkey, 'fooz')
# key must exist
ar(KeyError, self.db.file.setkey, 'fubar')
#
# class get
#
# invalid node id
ar(IndexError, self.db.issue.get, '99', 'title')
# invalid property name
ar(KeyError, self.db.status.get, '2', 'foo')
#
# class set
#
# invalid node id
ar(IndexError, self.db.issue.set, '99', title='foo')
# invalid property name
ar(KeyError, self.db.status.set, '1', foo='foo')
# string property
ar(TypeError, self.db.status.set, '1', name=1)
# key name clash
ar(ValueError, self.db.status.set, '2', name='unread')
# set up a valid issue for me to work on
id = self.db.issue.create(title="spam", status='1')
# invalid link index
ar(IndexError, self.db.issue.set, id, title='foo', status='bar')
# invalid link value
ar(ValueError, self.db.issue.set, id, title='foo', status=1)
# invalid multilink type
ar(TypeError, self.db.issue.set, id, title='foo', status='1',
nosy='hello')
# invalid multilink index type
ar(ValueError, self.db.issue.set, id, title='foo', status='1',
nosy=[1])
# invalid multilink index
ar(IndexError, self.db.issue.set, id, title='foo', status='1',
nosy=['10'])
# NOTE: the following increment the username to avoid problems
# within metakit's backend (it creates the node, and then sets the
# info, so the create (and by a fluke the username set) go through
# before the age/assignable/etc. set, which raises the exception)
# invalid number value
ar(TypeError, self.db.user.create, username='foo', age='a')
# invalid boolean value
ar(TypeError, self.db.user.create, username='foo2', assignable='true')
nid = self.db.user.create(username='foo3')
# invalid number value
ar(TypeError, self.db.user.set, nid, age='a')
# invalid boolean value
ar(TypeError, self.db.user.set, nid, assignable='true')
def testAuditors(self):
class test:
called = False
def call(self, *args): self.called = True
create = test()
self.db.user.audit('create', create.call)
self.db.user.create(username="mary")
self.assertEqual(create.called, True)
set = test()
self.db.user.audit('set', set.call)
self.db.user.set('1', username="joe")
self.assertEqual(set.called, True)
retire = test()
self.db.user.audit('retire', retire.call)
self.db.user.retire('1')
self.assertEqual(retire.called, True)
def testAuditorTwo(self):
class test:
n = 0
def a(self, *args): self.call_a = self.n; self.n += 1
def b(self, *args): self.call_b = self.n; self.n += 1
def c(self, *args): self.call_c = self.n; self.n += 1
test = test()
self.db.user.audit('create', test.b, 1)
self.db.user.audit('create', test.a, 1)
self.db.user.audit('create', test.c, 2)
self.db.user.create(username="mary")
self.assertEqual(test.call_a, 0)
self.assertEqual(test.call_b, 1)
self.assertEqual(test.call_c, 2)
def testDefault_Value(self):
new_issue=self.db.issue.create(title="title", deadline=date.Date('2016-6-30.22:39'))
# John Rouillard claims this should return the default value of 1 week for foo,
# but the hyperdb doesn't assign the default value for missing properties in the
# db on creation.
result=self.db.issue.get(new_issue, 'foo')
# When the defaultis automatically set by the hyperdb, change this to
# match the Interval test below.
self.assertEqual(result, None)
# but verify that the default value is retreivable
result=self.db.issue.properties['foo'].get_default_value()
self.assertEqual(result, date.Interval('-7d'))
def testQuietProperty(self):
# make sure that the quiet properties: "assignable" and "age" are not
# returned as part of the proplist
new_user=self.db.user.create(username="pete", age=10, assignable=False)
new_issue=self.db.issue.create(title="title", deadline=date.Date('2016-6-30.22:39'))
# change all quiet params. Verify they aren't returned in object.
# between this and the issue class every type represented in hyperdb
# should be initalized with a quiet parameter.
result=self.db.user.set(new_user, username="new", age=20, supervisor='3', assignable=True,
password=password.Password("3456"), rating=4, realname="newname")
self.assertEqual(result, {'supervisor': '3', 'username': "new"})
result=self.db.user.get(new_user, 'age')
self.assertEqual(result, 20)
# change all quiet params. Verify they aren't returned in object.
result=self.db.issue.set(new_issue, title="title2", deadline=date.Date('2016-7-13.22:39'),
assignedto="2", nosy=["3", "2"])
self.assertEqual(result, {'title': 'title2'})
# also test that we can make a property noisy
self.db.user.properties['age'].quiet=False
result=self.db.user.set(new_user, username="old", age=30, supervisor='2', assignable=False)
self.assertEqual(result, {'age': 30, 'supervisor': '2', 'username': "old"})
self.db.user.properties['age'].quiet=True