Code

Fix first part of Password handling security issue2550688 (thanks
[roundup.git] / test / db_test_base.py
1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17 #
18 # $Id: db_test_base.py,v 1.101 2008-08-19 01:40:59 richard Exp $
20 import unittest, os, shutil, errno, imp, sys, time, pprint, base64, os.path
21 # Python 2.3 ... 2.6 compatibility:
22 from roundup.anypy.sets_ import set
24 from roundup.hyperdb import String, Password, Link, Multilink, Date, \
25     Interval, DatabaseError, Boolean, Number, Node
26 from roundup.mailer import Mailer
27 from roundup import date, password, init, instance, configuration, \
28     roundupdb, i18n
30 from mocknull import MockNull
32 config = configuration.CoreConfig()
33 config.DATABASE = "db"
34 config.RDBMS_NAME = "rounduptest"
35 config.RDBMS_HOST = "localhost"
36 config.RDBMS_USER = "rounduptest"
37 config.RDBMS_PASSWORD = "rounduptest"
38 config.RDBMS_TEMPLATE = "template0"
39 #config.logging = MockNull()
40 # these TRACKER_WEB and MAIL_DOMAIN values are used in mailgw tests
41 config.MAIL_DOMAIN = "your.tracker.email.domain.example"
42 config.TRACKER_WEB = "http://tracker.example/cgi-bin/roundup.cgi/bugs/"
43 # uncomment the following to have excessive debug output from test cases
44 # FIXME: tracker logging level should be increased by -v arguments
45 #   to 'run_tests.py' script
46 #config.LOGGING_FILENAME = "/tmp/logfile"
47 #config.LOGGING_LEVEL = "DEBUG"
48 config.init_logging()
50 def setupTracker(dirname, backend="anydbm"):
51     """Install and initialize new tracker in dirname; return tracker instance.
53     If the directory exists, it is wiped out before the operation.
55     """
56     global config
57     try:
58         shutil.rmtree(dirname)
59     except OSError, error:
60         if error.errno not in (errno.ENOENT, errno.ESRCH): raise
61     # create the instance
62     init.install(dirname, os.path.join(os.path.dirname(__file__),
63                                        '..',
64                                        'share',
65                                        'roundup',
66                                        'templates',
67                                        'classic'))
68     init.write_select_db(dirname, backend)
69     config.save(os.path.join(dirname, 'config.ini'))
70     tracker = instance.open(dirname)
71     if tracker.exists():
72         tracker.nuke()
73         init.write_select_db(dirname, backend)
74     tracker.init(password.Password('sekrit'))
75     return tracker
77 def setupSchema(db, create, module):
78     status = module.Class(db, "status", name=String())
79     status.setkey("name")
80     priority = module.Class(db, "priority", name=String(), order=String())
81     priority.setkey("name")
82     user = module.Class(db, "user", username=String(), password=Password(),
83         assignable=Boolean(), age=Number(), roles=String(), address=String(),
84         supervisor=Link('user'),realname=String())
85     user.setkey("username")
86     file = module.FileClass(db, "file", name=String(), type=String(),
87         comment=String(indexme="yes"), fooz=Password())
88     file_nidx = module.FileClass(db, "file_nidx", content=String(indexme='no'))
89     issue = module.IssueClass(db, "issue", title=String(indexme="yes"),
90         status=Link("status"), nosy=Multilink("user"), deadline=Date(),
91         foo=Interval(), files=Multilink("file"), assignedto=Link('user'),
92         priority=Link('priority'), spam=Multilink('msg'),
93         feedback=Link('msg'))
94     stuff = module.Class(db, "stuff", stuff=String())
95     session = module.Class(db, 'session', title=String())
96     msg = module.FileClass(db, "msg", date=Date(),
97                            author=Link("user", do_journal='no'),
98                            files=Multilink('file'), inreplyto=String(),
99                            messageid=String(),
100                            recipients=Multilink("user", do_journal='no')
101                            )
102     session.disableJournalling()
103     db.post_init()
104     if create:
105         user.create(username="admin", roles='Admin',
106             password=password.Password('sekrit'))
107         user.create(username="fred", roles='User',
108             password=password.Password('sekrit'), address='fred@example.com')
109         status.create(name="unread")
110         status.create(name="in-progress")
111         status.create(name="testing")
112         status.create(name="resolved")
113         priority.create(name="feature", order="2")
114         priority.create(name="wish", order="3")
115         priority.create(name="bug", order="1")
116     db.commit()
118     # nosy tests require this
119     db.security.addPermissionToRole('User', 'View', 'msg')
121 class MyTestCase(unittest.TestCase):
122     def tearDown(self):
123         if hasattr(self, 'db'):
124             self.db.close()
125         if os.path.exists(config.DATABASE):
126             shutil.rmtree(config.DATABASE)
128     def open_database(self):
129         self.db = self.module.Database(config, 'admin')
132 if os.environ.has_key('LOGGING_LEVEL'):
133     from roundup import rlog
134     config.logging = rlog.BasicLogging()
135     config.logging.setLevel(os.environ['LOGGING_LEVEL'])
136     config.logging.getLogger('roundup.hyperdb').setFormat('%(message)s')
138 class commonDBTest(MyTestCase):
139     def setUp(self):
140         # remove previous test, ignore errors
141         if os.path.exists(config.DATABASE):
142             shutil.rmtree(config.DATABASE)
143         os.makedirs(config.DATABASE + '/files')
144         self.open_database()
145         setupSchema(self.db, 1, self.module)
147     def iterSetup(self, classname='issue'):
148         cls = getattr(self.db, classname)
149         def filt_iter(*args):
150             """ for checking equivalence of filter and filter_iter """
151             return list(cls.filter_iter(*args))
152         return self.assertEqual, cls.filter, filt_iter
154     def filteringSetupTransitiveSearch(self, classname='issue'):
155         u_m = {}
156         k = 30
157         for user in (
158                 {'username': 'ceo', 'age': 129},
159                 {'username': 'grouplead1', 'age': 29, 'supervisor': '3'},
160                 {'username': 'grouplead2', 'age': 29, 'supervisor': '3'},
161                 {'username': 'worker1', 'age': 25, 'supervisor' : '4'},
162                 {'username': 'worker2', 'age': 24, 'supervisor' : '4'},
163                 {'username': 'worker3', 'age': 23, 'supervisor' : '5'},
164                 {'username': 'worker4', 'age': 22, 'supervisor' : '5'},
165                 {'username': 'worker5', 'age': 21, 'supervisor' : '5'}):
166             u = self.db.user.create(**user)
167             u_m [u] = self.db.msg.create(author = u, content = ' '
168                 , date = date.Date ('2006-01-%s' % k))
169             k -= 1
170         i = date.Interval('-1d')
171         for issue in (
172                 {'title': 'ts1', 'status': '2', 'assignedto': '6',
173                     'priority': '3', 'messages' : [u_m ['6']], 'nosy' : ['4']},
174                 {'title': 'ts2', 'status': '1', 'assignedto': '6',
175                     'priority': '3', 'messages' : [u_m ['6']], 'nosy' : ['5']},
176                 {'title': 'ts4', 'status': '2', 'assignedto': '7',
177                     'priority': '3', 'messages' : [u_m ['7']]},
178                 {'title': 'ts5', 'status': '1', 'assignedto': '8',
179                     'priority': '3', 'messages' : [u_m ['8']]},
180                 {'title': 'ts6', 'status': '2', 'assignedto': '9',
181                     'priority': '3', 'messages' : [u_m ['9']]},
182                 {'title': 'ts7', 'status': '1', 'assignedto': '10',
183                     'priority': '3', 'messages' : [u_m ['10']]},
184                 {'title': 'ts8', 'status': '2', 'assignedto': '10',
185                     'priority': '3', 'messages' : [u_m ['10']], 'foo' : i},
186                 {'title': 'ts9', 'status': '1', 'assignedto': '10',
187                     'priority': '3', 'messages' : [u_m ['10'], u_m ['9']]}):
188             self.db.issue.create(**issue)
189         return self.iterSetup(classname)
192 class DBTest(commonDBTest):
194     def testRefresh(self):
195         self.db.refresh_database()
197     #
198     # automatic properties (well, the two easy ones anyway)
199     #
200     def testCreatorProperty(self):
201         i = self.db.issue
202         id1 = i.create(title='spam')
203         self.db.journaltag = 'fred'
204         id2 = i.create(title='spam')
205         self.assertNotEqual(id1, id2)
206         self.assertNotEqual(i.get(id1, 'creator'), i.get(id2, 'creator'))
208     def testActorProperty(self):
209         i = self.db.issue
210         id1 = i.create(title='spam')
211         self.db.journaltag = 'fred'
212         i.set(id1, title='asfasd')
213         self.assertNotEqual(i.get(id1, 'creator'), i.get(id1, 'actor'))
215     # ID number controls
216     def testIDGeneration(self):
217         id1 = self.db.issue.create(title="spam", status='1')
218         id2 = self.db.issue.create(title="eggs", status='2')
219         self.assertNotEqual(id1, id2)
220     def testIDSetting(self):
221         # XXX numeric ids
222         self.db.setid('issue', 10)
223         id2 = self.db.issue.create(title="eggs", status='2')
224         self.assertEqual('11', id2)
226     #
227     # basic operations
228     #
229     def testEmptySet(self):
230         id1 = self.db.issue.create(title="spam", status='1')
231         self.db.issue.set(id1)
233     # String
234     def testStringChange(self):
235         for commit in (0,1):
236             # test set & retrieve
237             nid = self.db.issue.create(title="spam", status='1')
238             self.assertEqual(self.db.issue.get(nid, 'title'), 'spam')
240             # change and make sure we retrieve the correct value
241             self.db.issue.set(nid, title='eggs')
242             if commit: self.db.commit()
243             self.assertEqual(self.db.issue.get(nid, 'title'), 'eggs')
245     def testStringUnset(self):
246         for commit in (0,1):
247             nid = self.db.issue.create(title="spam", status='1')
248             if commit: self.db.commit()
249             self.assertEqual(self.db.issue.get(nid, 'title'), 'spam')
250             # make sure we can unset
251             self.db.issue.set(nid, title=None)
252             if commit: self.db.commit()
253             self.assertEqual(self.db.issue.get(nid, "title"), None)
255     # FileClass "content" property (no unset test)
256     def testFileClassContentChange(self):
257         for commit in (0,1):
258             # test set & retrieve
259             nid = self.db.file.create(content="spam")
260             self.assertEqual(self.db.file.get(nid, 'content'), 'spam')
262             # change and make sure we retrieve the correct value
263             self.db.file.set(nid, content='eggs')
264             if commit: self.db.commit()
265             self.assertEqual(self.db.file.get(nid, 'content'), 'eggs')
267     def testStringUnicode(self):
268         # test set & retrieve
269         ustr = u'\xe4\xf6\xfc\u20ac'.encode('utf8')
270         nid = self.db.issue.create(title=ustr, status='1')
271         self.assertEqual(self.db.issue.get(nid, 'title'), ustr)
273         # change and make sure we retrieve the correct value
274         ustr2 = u'change \u20ac change'.encode('utf8')
275         self.db.issue.set(nid, title=ustr2)
276         self.db.commit()
277         self.assertEqual(self.db.issue.get(nid, 'title'), ustr2)
279     # Link
280     def testLinkChange(self):
281         self.assertRaises(IndexError, self.db.issue.create, title="spam",
282             status='100')
283         for commit in (0,1):
284             nid = self.db.issue.create(title="spam", status='1')
285             if commit: self.db.commit()
286             self.assertEqual(self.db.issue.get(nid, "status"), '1')
287             self.db.issue.set(nid, status='2')
288             if commit: self.db.commit()
289             self.assertEqual(self.db.issue.get(nid, "status"), '2')
291     def testLinkUnset(self):
292         for commit in (0,1):
293             nid = self.db.issue.create(title="spam", status='1')
294             if commit: self.db.commit()
295             self.db.issue.set(nid, status=None)
296             if commit: self.db.commit()
297             self.assertEqual(self.db.issue.get(nid, "status"), None)
299     # Multilink
300     def testMultilinkChange(self):
301         for commit in (0,1):
302             self.assertRaises(IndexError, self.db.issue.create, title="spam",
303                 nosy=['foo%s'%commit])
304             u1 = self.db.user.create(username='foo%s'%commit)
305             u2 = self.db.user.create(username='bar%s'%commit)
306             nid = self.db.issue.create(title="spam", nosy=[u1])
307             if commit: self.db.commit()
308             self.assertEqual(self.db.issue.get(nid, "nosy"), [u1])
309             self.db.issue.set(nid, nosy=[])
310             if commit: self.db.commit()
311             self.assertEqual(self.db.issue.get(nid, "nosy"), [])
312             self.db.issue.set(nid, nosy=[u1,u2])
313             if commit: self.db.commit()
314             l = [u1,u2]; l.sort()
315             m = self.db.issue.get(nid, "nosy"); m.sort()
316             self.assertEqual(l, m)
318             # verify that when we pass None to an Multilink it sets
319             # it to an empty list
320             self.db.issue.set(nid, nosy=None)
321             if commit: self.db.commit()
322             self.assertEqual(self.db.issue.get(nid, "nosy"), [])
324     def testMultilinkChangeIterable(self):
325         for commit in (0,1):
326             # invalid nosy value assertion
327             self.assertRaises(IndexError, self.db.issue.create, title='spam',
328                 nosy=['foo%s'%commit])
329             # invalid type for nosy create
330             self.assertRaises(TypeError, self.db.issue.create, title='spam',
331                 nosy=1)
332             u1 = self.db.user.create(username='foo%s'%commit)
333             u2 = self.db.user.create(username='bar%s'%commit)
334             # try a couple of the built-in iterable types to make
335             # sure that we accept them and handle them properly
336             # try a set as input for the multilink
337             nid = self.db.issue.create(title="spam", nosy=set(u1))
338             if commit: self.db.commit()
339             self.assertEqual(self.db.issue.get(nid, "nosy"), [u1])
340             self.assertRaises(TypeError, self.db.issue.set, nid,
341                 nosy='invalid type')
342             # test with a tuple
343             self.db.issue.set(nid, nosy=tuple())
344             if commit: self.db.commit()
345             self.assertEqual(self.db.issue.get(nid, "nosy"), [])
346             # make sure we accept a frozen set
347             self.db.issue.set(nid, nosy=set([u1,u2]))
348             if commit: self.db.commit()
349             l = [u1,u2]; l.sort()
350             m = self.db.issue.get(nid, "nosy"); m.sort()
351             self.assertEqual(l, m)
354 # XXX one day, maybe...
355 #    def testMultilinkOrdering(self):
356 #        for i in range(10):
357 #            self.db.user.create(username='foo%s'%i)
358 #        i = self.db.issue.create(title="spam", nosy=['5','3','12','4'])
359 #        self.db.commit()
360 #        l = self.db.issue.get(i, "nosy")
361 #        # all backends should return the Multilink numeric-id-sorted
362 #        self.assertEqual(l, ['3', '4', '5', '12'])
364     # Date
365     def testDateChange(self):
366         self.assertRaises(TypeError, self.db.issue.create,
367             title='spam', deadline=1)
368         for commit in (0,1):
369             nid = self.db.issue.create(title="spam", status='1')
370             self.assertRaises(TypeError, self.db.issue.set, nid, deadline=1)
371             a = self.db.issue.get(nid, "deadline")
372             if commit: self.db.commit()
373             self.db.issue.set(nid, deadline=date.Date())
374             b = self.db.issue.get(nid, "deadline")
375             if commit: self.db.commit()
376             self.assertNotEqual(a, b)
377             self.assertNotEqual(b, date.Date('1970-1-1.00:00:00'))
378             # The 1970 date will fail for metakit -- it is used
379             # internally for storing NULL. The others would, too
380             # because metakit tries to convert date.timestamp to an int
381             # for storing and fails with an overflow.
382             for d in [date.Date (x) for x in '2038', '1970', '0033', '9999']:
383                 self.db.issue.set(nid, deadline=d)
384                 if commit: self.db.commit()
385                 c = self.db.issue.get(nid, "deadline")
386                 self.assertEqual(c, d)
388     def testDateLeapYear(self):
389         nid = self.db.issue.create(title='spam', status='1',
390             deadline=date.Date('2008-02-29'))
391         self.assertEquals(str(self.db.issue.get(nid, 'deadline')),
392             '2008-02-29.00:00:00')
393         self.assertEquals(self.db.issue.filter(None,
394             {'deadline': '2008-02-29'}), [nid])
395         self.assertEquals(list(self.db.issue.filter_iter(None,
396             {'deadline': '2008-02-29'})), [nid])
397         self.db.issue.set(nid, deadline=date.Date('2008-03-01'))
398         self.assertEquals(str(self.db.issue.get(nid, 'deadline')),
399             '2008-03-01.00:00:00')
400         self.assertEquals(self.db.issue.filter(None,
401             {'deadline': '2008-02-29'}), [])
402         self.assertEquals(list(self.db.issue.filter_iter(None,
403             {'deadline': '2008-02-29'})), [])
405     def testDateUnset(self):
406         for commit in (0,1):
407             nid = self.db.issue.create(title="spam", status='1')
408             self.db.issue.set(nid, deadline=date.Date())
409             if commit: self.db.commit()
410             self.assertNotEqual(self.db.issue.get(nid, "deadline"), None)
411             self.db.issue.set(nid, deadline=None)
412             if commit: self.db.commit()
413             self.assertEqual(self.db.issue.get(nid, "deadline"), None)
415     # Interval
416     def testIntervalChange(self):
417         self.assertRaises(TypeError, self.db.issue.create,
418             title='spam', foo=1)
419         for commit in (0,1):
420             nid = self.db.issue.create(title="spam", status='1')
421             self.assertRaises(TypeError, self.db.issue.set, nid, foo=1)
422             if commit: self.db.commit()
423             a = self.db.issue.get(nid, "foo")
424             i = date.Interval('-1d')
425             self.db.issue.set(nid, foo=i)
426             if commit: self.db.commit()
427             self.assertNotEqual(self.db.issue.get(nid, "foo"), a)
428             self.assertEqual(i, self.db.issue.get(nid, "foo"))
429             j = date.Interval('1y')
430             self.db.issue.set(nid, foo=j)
431             if commit: self.db.commit()
432             self.assertNotEqual(self.db.issue.get(nid, "foo"), i)
433             self.assertEqual(j, self.db.issue.get(nid, "foo"))
435     def testIntervalUnset(self):
436         for commit in (0,1):
437             nid = self.db.issue.create(title="spam", status='1')
438             self.db.issue.set(nid, foo=date.Interval('-1d'))
439             if commit: self.db.commit()
440             self.assertNotEqual(self.db.issue.get(nid, "foo"), None)
441             self.db.issue.set(nid, foo=None)
442             if commit: self.db.commit()
443             self.assertEqual(self.db.issue.get(nid, "foo"), None)
445     # Boolean
446     def testBooleanSet(self):
447         nid = self.db.user.create(username='one', assignable=1)
448         self.assertEqual(self.db.user.get(nid, "assignable"), 1)
449         nid = self.db.user.create(username='two', assignable=0)
450         self.assertEqual(self.db.user.get(nid, "assignable"), 0)
452     def testBooleanChange(self):
453         userid = self.db.user.create(username='foo', assignable=1)
454         self.assertEqual(1, self.db.user.get(userid, 'assignable'))
455         self.db.user.set(userid, assignable=0)
456         self.assertEqual(self.db.user.get(userid, 'assignable'), 0)
457         self.db.user.set(userid, assignable=1)
458         self.assertEqual(self.db.user.get(userid, 'assignable'), 1)
460     def testBooleanUnset(self):
461         nid = self.db.user.create(username='foo', assignable=1)
462         self.db.user.set(nid, assignable=None)
463         self.assertEqual(self.db.user.get(nid, "assignable"), None)
465     # Number
466     def testNumberChange(self):
467         nid = self.db.user.create(username='foo', age=1)
468         self.assertEqual(1, self.db.user.get(nid, 'age'))
469         self.db.user.set(nid, age=3)
470         self.assertNotEqual(self.db.user.get(nid, 'age'), 1)
471         self.db.user.set(nid, age=1.0)
472         self.assertEqual(self.db.user.get(nid, 'age'), 1)
473         self.db.user.set(nid, age=0)
474         self.assertEqual(self.db.user.get(nid, 'age'), 0)
476         nid = self.db.user.create(username='bar', age=0)
477         self.assertEqual(self.db.user.get(nid, 'age'), 0)
479     def testNumberUnset(self):
480         nid = self.db.user.create(username='foo', age=1)
481         self.db.user.set(nid, age=None)
482         self.assertEqual(self.db.user.get(nid, "age"), None)
484     # Password
485     def testPasswordChange(self):
486         x = password.Password('x')
487         userid = self.db.user.create(username='foo', password=x)
488         self.assertEqual(x, self.db.user.get(userid, 'password'))
489         self.assertEqual(self.db.user.get(userid, 'password'), 'x')
490         y = password.Password('y')
491         self.db.user.set(userid, password=y)
492         self.assertEqual(self.db.user.get(userid, 'password'), 'y')
493         self.assertRaises(TypeError, self.db.user.create, userid,
494             username='bar', password='x')
495         self.assertRaises(TypeError, self.db.user.set, userid, password='x')
497     def testPasswordUnset(self):
498         x = password.Password('x')
499         nid = self.db.user.create(username='foo', password=x)
500         self.db.user.set(nid, assignable=None)
501         self.assertEqual(self.db.user.get(nid, "assignable"), None)
503     # key value
504     def testKeyValue(self):
505         self.assertRaises(ValueError, self.db.user.create)
507         newid = self.db.user.create(username="spam")
508         self.assertEqual(self.db.user.lookup('spam'), newid)
509         self.db.commit()
510         self.assertEqual(self.db.user.lookup('spam'), newid)
511         self.db.user.retire(newid)
512         self.assertRaises(KeyError, self.db.user.lookup, 'spam')
514         # use the key again now that the old is retired
515         newid2 = self.db.user.create(username="spam")
516         self.assertNotEqual(newid, newid2)
517         # try to restore old node. this shouldn't succeed!
518         self.assertRaises(KeyError, self.db.user.restore, newid)
520         self.assertRaises(TypeError, self.db.issue.lookup, 'fubar')
522     # label property
523     def testLabelProp(self):
524         # key prop
525         self.assertEqual(self.db.status.labelprop(), 'name')
526         self.assertEqual(self.db.user.labelprop(), 'username')
527         # title
528         self.assertEqual(self.db.issue.labelprop(), 'title')
529         # name
530         self.assertEqual(self.db.file.labelprop(), 'name')
531         # id
532         self.assertEqual(self.db.stuff.labelprop(default_to_id=1), 'id')
534     # retirement
535     def testRetire(self):
536         self.db.issue.create(title="spam", status='1')
537         b = self.db.status.get('1', 'name')
538         a = self.db.status.list()
539         nodeids = self.db.status.getnodeids()
540         self.db.status.retire('1')
541         others = nodeids[:]
542         others.remove('1')
544         self.assertEqual(set(self.db.status.getnodeids()),
545             set(nodeids))
546         self.assertEqual(set(self.db.status.getnodeids(retired=True)),
547             set(['1']))
548         self.assertEqual(set(self.db.status.getnodeids(retired=False)),
549             set(others))
551         self.assert_(self.db.status.is_retired('1'))
553         # make sure the list is different
554         self.assertNotEqual(a, self.db.status.list())
556         # can still access the node if necessary
557         self.assertEqual(self.db.status.get('1', 'name'), b)
558         self.assertRaises(IndexError, self.db.status.set, '1', name='hello')
559         self.db.commit()
560         self.assert_(self.db.status.is_retired('1'))
561         self.assertEqual(self.db.status.get('1', 'name'), b)
562         self.assertNotEqual(a, self.db.status.list())
564         # try to restore retired node
565         self.db.status.restore('1')
567         self.assert_(not self.db.status.is_retired('1'))
569     def testCacheCreateSet(self):
570         self.db.issue.create(title="spam", status='1')
571         a = self.db.issue.get('1', 'title')
572         self.assertEqual(a, 'spam')
573         self.db.issue.set('1', title='ham')
574         b = self.db.issue.get('1', 'title')
575         self.assertEqual(b, 'ham')
577     def testSerialisation(self):
578         nid = self.db.issue.create(title="spam", status='1',
579             deadline=date.Date(), foo=date.Interval('-1d'))
580         self.db.commit()
581         assert isinstance(self.db.issue.get(nid, 'deadline'), date.Date)
582         assert isinstance(self.db.issue.get(nid, 'foo'), date.Interval)
583         uid = self.db.user.create(username="fozzy",
584             password=password.Password('t. bear'))
585         self.db.commit()
586         assert isinstance(self.db.user.get(uid, 'password'), password.Password)
588     def testTransactions(self):
589         # remember the number of items we started
590         num_issues = len(self.db.issue.list())
591         num_files = self.db.numfiles()
592         self.db.issue.create(title="don't commit me!", status='1')
593         self.assertNotEqual(num_issues, len(self.db.issue.list()))
594         self.db.rollback()
595         self.assertEqual(num_issues, len(self.db.issue.list()))
596         self.db.issue.create(title="please commit me!", status='1')
597         self.assertNotEqual(num_issues, len(self.db.issue.list()))
598         self.db.commit()
599         self.assertNotEqual(num_issues, len(self.db.issue.list()))
600         self.db.rollback()
601         self.assertNotEqual(num_issues, len(self.db.issue.list()))
602         self.db.file.create(name="test", type="text/plain", content="hi")
603         self.db.rollback()
604         self.assertEqual(num_files, self.db.numfiles())
605         for i in range(10):
606             self.db.file.create(name="test", type="text/plain",
607                     content="hi %d"%(i))
608             self.db.commit()
609         num_files2 = self.db.numfiles()
610         self.assertNotEqual(num_files, num_files2)
611         self.db.file.create(name="test", type="text/plain", content="hi")
612         self.db.rollback()
613         self.assertNotEqual(num_files, self.db.numfiles())
614         self.assertEqual(num_files2, self.db.numfiles())
616         # rollback / cache interaction
617         name1 = self.db.user.get('1', 'username')
618         self.db.user.set('1', username = name1+name1)
619         # get the prop so the info's forced into the cache (if there is one)
620         self.db.user.get('1', 'username')
621         self.db.rollback()
622         name2 = self.db.user.get('1', 'username')
623         self.assertEqual(name1, name2)
625     def testDestroyBlob(self):
626         # destroy an uncommitted blob
627         f1 = self.db.file.create(content='hello', type="text/plain")
628         self.db.commit()
629         fn = self.db.filename('file', f1)
630         self.db.file.destroy(f1)
631         self.db.commit()
632         self.assertEqual(os.path.exists(fn), False)
634     def testDestroyNoJournalling(self):
635         self.innerTestDestroy(klass=self.db.session)
637     def testDestroyJournalling(self):
638         self.innerTestDestroy(klass=self.db.issue)
640     def innerTestDestroy(self, klass):
641         newid = klass.create(title='Mr Friendly')
642         n = len(klass.list())
643         self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
644         count = klass.count()
645         klass.destroy(newid)
646         self.assertNotEqual(count, klass.count())
647         self.assertRaises(IndexError, klass.get, newid, 'title')
648         self.assertNotEqual(len(klass.list()), n)
649         if klass.do_journal:
650             self.assertRaises(IndexError, klass.history, newid)
652         # now with a commit
653         newid = klass.create(title='Mr Friendly')
654         n = len(klass.list())
655         self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
656         self.db.commit()
657         count = klass.count()
658         klass.destroy(newid)
659         self.assertNotEqual(count, klass.count())
660         self.assertRaises(IndexError, klass.get, newid, 'title')
661         self.db.commit()
662         self.assertRaises(IndexError, klass.get, newid, 'title')
663         self.assertNotEqual(len(klass.list()), n)
664         if klass.do_journal:
665             self.assertRaises(IndexError, klass.history, newid)
667         # now with a rollback
668         newid = klass.create(title='Mr Friendly')
669         n = len(klass.list())
670         self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
671         self.db.commit()
672         count = klass.count()
673         klass.destroy(newid)
674         self.assertNotEqual(len(klass.list()), n)
675         self.assertRaises(IndexError, klass.get, newid, 'title')
676         self.db.rollback()
677         self.assertEqual(count, klass.count())
678         self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
679         self.assertEqual(len(klass.list()), n)
680         if klass.do_journal:
681             self.assertNotEqual(klass.history(newid), [])
683     def testExceptions(self):
684         # this tests the exceptions that should be raised
685         ar = self.assertRaises
687         ar(KeyError, self.db.getclass, 'fubar')
689         #
690         # class create
691         #
692         # string property
693         ar(TypeError, self.db.status.create, name=1)
694         # id, creation, creator and activity properties are reserved
695         ar(KeyError, self.db.status.create, id=1)
696         ar(KeyError, self.db.status.create, creation=1)
697         ar(KeyError, self.db.status.create, creator=1)
698         ar(KeyError, self.db.status.create, activity=1)
699         ar(KeyError, self.db.status.create, actor=1)
700         # invalid property name
701         ar(KeyError, self.db.status.create, foo='foo')
702         # key name clash
703         ar(ValueError, self.db.status.create, name='unread')
704         # invalid link index
705         ar(IndexError, self.db.issue.create, title='foo', status='bar')
706         # invalid link value
707         ar(ValueError, self.db.issue.create, title='foo', status=1)
708         # invalid multilink type
709         ar(TypeError, self.db.issue.create, title='foo', status='1',
710             nosy='hello')
711         # invalid multilink index type
712         ar(ValueError, self.db.issue.create, title='foo', status='1',
713             nosy=[1])
714         # invalid multilink index
715         ar(IndexError, self.db.issue.create, title='foo', status='1',
716             nosy=['10'])
718         #
719         # key property
720         #
721         # key must be a String
722         ar(TypeError, self.db.file.setkey, 'fooz')
723         # key must exist
724         ar(KeyError, self.db.file.setkey, 'fubar')
726         #
727         # class get
728         #
729         # invalid node id
730         ar(IndexError, self.db.issue.get, '99', 'title')
731         # invalid property name
732         ar(KeyError, self.db.status.get, '2', 'foo')
734         #
735         # class set
736         #
737         # invalid node id
738         ar(IndexError, self.db.issue.set, '99', title='foo')
739         # invalid property name
740         ar(KeyError, self.db.status.set, '1', foo='foo')
741         # string property
742         ar(TypeError, self.db.status.set, '1', name=1)
743         # key name clash
744         ar(ValueError, self.db.status.set, '2', name='unread')
745         # set up a valid issue for me to work on
746         id = self.db.issue.create(title="spam", status='1')
747         # invalid link index
748         ar(IndexError, self.db.issue.set, id, title='foo', status='bar')
749         # invalid link value
750         ar(ValueError, self.db.issue.set, id, title='foo', status=1)
751         # invalid multilink type
752         ar(TypeError, self.db.issue.set, id, title='foo', status='1',
753             nosy='hello')
754         # invalid multilink index type
755         ar(ValueError, self.db.issue.set, id, title='foo', status='1',
756             nosy=[1])
757         # invalid multilink index
758         ar(IndexError, self.db.issue.set, id, title='foo', status='1',
759             nosy=['10'])
760         # NOTE: the following increment the username to avoid problems
761         # within metakit's backend (it creates the node, and then sets the
762         # info, so the create (and by a fluke the username set) go through
763         # before the age/assignable/etc. set, which raises the exception)
764         # invalid number value
765         ar(TypeError, self.db.user.create, username='foo', age='a')
766         # invalid boolean value
767         ar(TypeError, self.db.user.create, username='foo2', assignable='true')
768         nid = self.db.user.create(username='foo3')
769         # invalid number value
770         ar(TypeError, self.db.user.set, nid, age='a')
771         # invalid boolean value
772         ar(TypeError, self.db.user.set, nid, assignable='true')
774     def testAuditors(self):
775         class test:
776             called = False
777             def call(self, *args): self.called = True
778         create = test()
780         self.db.user.audit('create', create.call)
781         self.db.user.create(username="mary")
782         self.assertEqual(create.called, True)
784         set = test()
785         self.db.user.audit('set', set.call)
786         self.db.user.set('1', username="joe")
787         self.assertEqual(set.called, True)
789         retire = test()
790         self.db.user.audit('retire', retire.call)
791         self.db.user.retire('1')
792         self.assertEqual(retire.called, True)
794     def testAuditorTwo(self):
795         class test:
796             n = 0
797             def a(self, *args): self.call_a = self.n; self.n += 1
798             def b(self, *args): self.call_b = self.n; self.n += 1
799             def c(self, *args): self.call_c = self.n; self.n += 1
800         test = test()
801         self.db.user.audit('create', test.b, 1)
802         self.db.user.audit('create', test.a, 1)
803         self.db.user.audit('create', test.c, 2)
804         self.db.user.create(username="mary")
805         self.assertEqual(test.call_a, 0)
806         self.assertEqual(test.call_b, 1)
807         self.assertEqual(test.call_c, 2)
809     def testJournals(self):
810         muid = self.db.user.create(username="mary")
811         self.db.user.create(username="pete")
812         self.db.issue.create(title="spam", status='1')
813         self.db.commit()
815         # journal entry for issue create
816         journal = self.db.getjournal('issue', '1')
817         self.assertEqual(1, len(journal))
818         (nodeid, date_stamp, journaltag, action, params) = journal[0]
819         self.assertEqual(nodeid, '1')
820         self.assertEqual(journaltag, self.db.user.lookup('admin'))
821         self.assertEqual(action, 'create')
822         keys = params.keys()
823         keys.sort()
824         self.assertEqual(keys, [])
826         # journal entry for link
827         journal = self.db.getjournal('user', '1')
828         self.assertEqual(1, len(journal))
829         self.db.issue.set('1', assignedto='1')
830         self.db.commit()
831         journal = self.db.getjournal('user', '1')
832         self.assertEqual(2, len(journal))
833         (nodeid, date_stamp, journaltag, action, params) = journal[1]
834         self.assertEqual('1', nodeid)
835         self.assertEqual('1', journaltag)
836         self.assertEqual('link', action)
837         self.assertEqual(('issue', '1', 'assignedto'), params)
839         # wait a bit to keep proper order of journal entries
840         time.sleep(0.01)
841         # journal entry for unlink
842         self.db.setCurrentUser('mary')
843         self.db.issue.set('1', assignedto='2')
844         self.db.commit()
845         journal = self.db.getjournal('user', '1')
846         self.assertEqual(3, len(journal))
847         (nodeid, date_stamp, journaltag, action, params) = journal[2]
848         self.assertEqual('1', nodeid)
849         self.assertEqual(muid, journaltag)
850         self.assertEqual('unlink', action)
851         self.assertEqual(('issue', '1', 'assignedto'), params)
853         # test disabling journalling
854         # ... get the last entry
855         jlen = len(self.db.getjournal('user', '1'))
856         self.db.issue.disableJournalling()
857         self.db.issue.set('1', title='hello world')
858         self.db.commit()
859         # see if the change was journalled when it shouldn't have been
860         self.assertEqual(jlen,  len(self.db.getjournal('user', '1')))
861         jlen = len(self.db.getjournal('issue', '1'))
862         self.db.issue.enableJournalling()
863         self.db.issue.set('1', title='hello world 2')
864         self.db.commit()
865         # see if the change was journalled
866         self.assertNotEqual(jlen,  len(self.db.getjournal('issue', '1')))
868     def testJournalPreCommit(self):
869         id = self.db.user.create(username="mary")
870         self.assertEqual(len(self.db.getjournal('user', id)), 1)
871         self.db.commit()
873     def testPack(self):
874         id = self.db.issue.create(title="spam", status='1')
875         self.db.commit()
876         time.sleep(1)
877         self.db.issue.set(id, status='2')
878         self.db.commit()
880         # sleep for at least a second, then get a date to pack at
881         time.sleep(1)
882         pack_before = date.Date('.')
884         # wait another second and add one more entry
885         time.sleep(1)
886         self.db.issue.set(id, status='3')
887         self.db.commit()
888         jlen = len(self.db.getjournal('issue', id))
890         # pack
891         self.db.pack(pack_before)
893         # we should have the create and last set entries now
894         self.assertEqual(jlen-1, len(self.db.getjournal('issue', id)))
896     def testIndexerSearching(self):
897         f1 = self.db.file.create(content='hello', type="text/plain")
898         # content='world' has the wrong content-type and won't be indexed
899         f2 = self.db.file.create(content='world', type="text/frozz",
900             comment='blah blah')
901         i1 = self.db.issue.create(files=[f1, f2], title="flebble plop")
902         i2 = self.db.issue.create(title="flebble the frooz")
903         self.db.commit()
904         self.assertEquals(self.db.indexer.search([], self.db.issue), {})
905         self.assertEquals(self.db.indexer.search(['hello'], self.db.issue),
906             {i1: {'files': [f1]}})
907         # content='world' has the wrong content-type and shouldn't be indexed
908         self.assertEquals(self.db.indexer.search(['world'], self.db.issue), {})
909         self.assertEquals(self.db.indexer.search(['frooz'], self.db.issue),
910             {i2: {}})
911         self.assertEquals(self.db.indexer.search(['flebble'], self.db.issue),
912             {i1: {}, i2: {}})
914         # test AND'ing of search terms
915         self.assertEquals(self.db.indexer.search(['frooz', 'flebble'],
916             self.db.issue), {i2: {}})
918         # unindexed stopword
919         self.assertEquals(self.db.indexer.search(['the'], self.db.issue), {})
921     def testIndexerSearchingLink(self):
922         m1 = self.db.msg.create(content="one two")
923         i1 = self.db.issue.create(messages=[m1])
924         m2 = self.db.msg.create(content="two three")
925         i2 = self.db.issue.create(feedback=m2)
926         self.db.commit()
927         self.assertEquals(self.db.indexer.search(['two'], self.db.issue),
928             {i1: {'messages': [m1]}, i2: {'feedback': [m2]}})
930     def testIndexerSearchMulti(self):
931         m1 = self.db.msg.create(content="one two")
932         m2 = self.db.msg.create(content="two three")
933         i1 = self.db.issue.create(messages=[m1])
934         i2 = self.db.issue.create(spam=[m2])
935         self.db.commit()
936         self.assertEquals(self.db.indexer.search([], self.db.issue), {})
937         self.assertEquals(self.db.indexer.search(['one'], self.db.issue),
938             {i1: {'messages': [m1]}})
939         self.assertEquals(self.db.indexer.search(['two'], self.db.issue),
940             {i1: {'messages': [m1]}, i2: {'spam': [m2]}})
941         self.assertEquals(self.db.indexer.search(['three'], self.db.issue),
942             {i2: {'spam': [m2]}})
944     def testReindexingChange(self):
945         search = self.db.indexer.search
946         issue = self.db.issue
947         i1 = issue.create(title="flebble plop")
948         i2 = issue.create(title="flebble frooz")
949         self.db.commit()
950         self.assertEquals(search(['plop'], issue), {i1: {}})
951         self.assertEquals(search(['flebble'], issue), {i1: {}, i2: {}})
953         # change i1's title
954         issue.set(i1, title="plop")
955         self.db.commit()
956         self.assertEquals(search(['plop'], issue), {i1: {}})
957         self.assertEquals(search(['flebble'], issue), {i2: {}})
959     def testReindexingClear(self):
960         search = self.db.indexer.search
961         issue = self.db.issue
962         i1 = issue.create(title="flebble plop")
963         i2 = issue.create(title="flebble frooz")
964         self.db.commit()
965         self.assertEquals(search(['plop'], issue), {i1: {}})
966         self.assertEquals(search(['flebble'], issue), {i1: {}, i2: {}})
968         # unset i1's title
969         issue.set(i1, title="")
970         self.db.commit()
971         self.assertEquals(search(['plop'], issue), {})
972         self.assertEquals(search(['flebble'], issue), {i2: {}})
974     def testFileClassReindexing(self):
975         f1 = self.db.file.create(content='hello')
976         f2 = self.db.file.create(content='hello, world')
977         i1 = self.db.issue.create(files=[f1, f2])
978         self.db.commit()
979         d = self.db.indexer.search(['hello'], self.db.issue)
980         self.assert_(d.has_key(i1))
981         d[i1]['files'].sort()
982         self.assertEquals(d, {i1: {'files': [f1, f2]}})
983         self.assertEquals(self.db.indexer.search(['world'], self.db.issue),
984             {i1: {'files': [f2]}})
985         self.db.file.set(f1, content="world")
986         self.db.commit()
987         d = self.db.indexer.search(['world'], self.db.issue)
988         d[i1]['files'].sort()
989         self.assertEquals(d, {i1: {'files': [f1, f2]}})
990         self.assertEquals(self.db.indexer.search(['hello'], self.db.issue),
991             {i1: {'files': [f2]}})
993     def testFileClassIndexingNoNoNo(self):
994         f1 = self.db.file.create(content='hello')
995         self.db.commit()
996         self.assertEquals(self.db.indexer.search(['hello'], self.db.file),
997             {'1': {}})
999         f1 = self.db.file_nidx.create(content='hello')
1000         self.db.commit()
1001         self.assertEquals(self.db.indexer.search(['hello'], self.db.file_nidx),
1002             {})
1004     def testForcedReindexing(self):
1005         self.db.issue.create(title="flebble frooz")
1006         self.db.commit()
1007         self.assertEquals(self.db.indexer.search(['flebble'], self.db.issue),
1008             {'1': {}})
1009         self.db.indexer.quiet = 1
1010         self.db.indexer.force_reindex()
1011         self.db.post_init()
1012         self.db.indexer.quiet = 9
1013         self.assertEquals(self.db.indexer.search(['flebble'], self.db.issue),
1014             {'1': {}})
1016     def testIndexingPropertiesOnImport(self):
1017         # import an issue
1018         title = 'Bzzt'
1019         nodeid = self.db.issue.import_list(['title', 'messages', 'files',
1020             'spam', 'nosy', 'superseder'], [repr(title), '[]', '[]',
1021             '[]', '[]', '[]'])
1022         self.db.commit()
1024         # Content of title attribute is indexed
1025         self.assertEquals(self.db.indexer.search([title], self.db.issue),
1026             {str(nodeid):{}})
1029     #
1030     # searching tests follow
1031     #
1032     def testFindIncorrectProperty(self):
1033         self.assertRaises(TypeError, self.db.issue.find, title='fubar')
1035     def _find_test_setup(self):
1036         self.db.file.create(content='')
1037         self.db.file.create(content='')
1038         self.db.user.create(username='')
1039         one = self.db.issue.create(status="1", nosy=['1'])
1040         two = self.db.issue.create(status="2", nosy=['2'], files=['1'],
1041             assignedto='2')
1042         three = self.db.issue.create(status="1", nosy=['1','2'])
1043         four = self.db.issue.create(status="3", assignedto='1',
1044             files=['1','2'])
1045         return one, two, three, four
1047     def testFindLink(self):
1048         one, two, three, four = self._find_test_setup()
1049         got = self.db.issue.find(status='1')
1050         got.sort()
1051         self.assertEqual(got, [one, three])
1052         got = self.db.issue.find(status={'1':1})
1053         got.sort()
1054         self.assertEqual(got, [one, three])
1056     def testFindLinkFail(self):
1057         self._find_test_setup()
1058         self.assertEqual(self.db.issue.find(status='4'), [])
1059         self.assertEqual(self.db.issue.find(status={'4':1}), [])
1061     def testFindLinkUnset(self):
1062         one, two, three, four = self._find_test_setup()
1063         got = self.db.issue.find(assignedto=None)
1064         got.sort()
1065         self.assertEqual(got, [one, three])
1066         got = self.db.issue.find(assignedto={None:1})
1067         got.sort()
1068         self.assertEqual(got, [one, three])
1070     def testFindMultipleLink(self):
1071         one, two, three, four = self._find_test_setup()
1072         l = self.db.issue.find(status={'1':1, '3':1})
1073         l.sort()
1074         self.assertEqual(l, [one, three, four])
1075         l = self.db.issue.find(assignedto={None:1, '1':1})
1076         l.sort()
1077         self.assertEqual(l, [one, three, four])
1079     def testFindMultilink(self):
1080         one, two, three, four = self._find_test_setup()
1081         got = self.db.issue.find(nosy='2')
1082         got.sort()
1083         self.assertEqual(got, [two, three])
1084         got = self.db.issue.find(nosy={'2':1})
1085         got.sort()
1086         self.assertEqual(got, [two, three])
1087         got = self.db.issue.find(nosy={'2':1}, files={})
1088         got.sort()
1089         self.assertEqual(got, [two, three])
1091     def testFindMultiMultilink(self):
1092         one, two, three, four = self._find_test_setup()
1093         got = self.db.issue.find(nosy='2', files='1')
1094         got.sort()
1095         self.assertEqual(got, [two, three, four])
1096         got = self.db.issue.find(nosy={'2':1}, files={'1':1})
1097         got.sort()
1098         self.assertEqual(got, [two, three, four])
1100     def testFindMultilinkFail(self):
1101         self._find_test_setup()
1102         self.assertEqual(self.db.issue.find(nosy='3'), [])
1103         self.assertEqual(self.db.issue.find(nosy={'3':1}), [])
1105     def testFindMultilinkUnset(self):
1106         self._find_test_setup()
1107         self.assertEqual(self.db.issue.find(nosy={}), [])
1109     def testFindLinkAndMultilink(self):
1110         one, two, three, four = self._find_test_setup()
1111         got = self.db.issue.find(status='1', nosy='2')
1112         got.sort()
1113         self.assertEqual(got, [one, two, three])
1114         got = self.db.issue.find(status={'1':1}, nosy={'2':1})
1115         got.sort()
1116         self.assertEqual(got, [one, two, three])
1118     def testFindRetired(self):
1119         one, two, three, four = self._find_test_setup()
1120         self.assertEqual(len(self.db.issue.find(status='1')), 2)
1121         self.db.issue.retire(one)
1122         self.assertEqual(len(self.db.issue.find(status='1')), 1)
1124     def testStringFind(self):
1125         self.assertRaises(TypeError, self.db.issue.stringFind, status='1')
1127         ids = []
1128         ids.append(self.db.issue.create(title="spam"))
1129         self.db.issue.create(title="not spam")
1130         ids.append(self.db.issue.create(title="spam"))
1131         ids.sort()
1132         got = self.db.issue.stringFind(title='spam')
1133         got.sort()
1134         self.assertEqual(got, ids)
1135         self.assertEqual(self.db.issue.stringFind(title='fubar'), [])
1137         # test retiring a node
1138         self.db.issue.retire(ids[0])
1139         self.assertEqual(len(self.db.issue.stringFind(title='spam')), 1)
1141     def filteringSetup(self, classname='issue'):
1142         for user in (
1143                 {'username': 'bleep', 'age': 1, 'assignable': True},
1144                 {'username': 'blop', 'age': 1.5, 'assignable': True},
1145                 {'username': 'blorp', 'age': 2, 'assignable': False}):
1146             self.db.user.create(**user)
1147         file_content = ''.join([chr(i) for i in range(255)])
1148         f = self.db.file.create(content=file_content)
1149         for issue in (
1150                 {'title': 'issue one', 'status': '2', 'assignedto': '1',
1151                     'foo': date.Interval('1:10'), 'priority': '3',
1152                     'deadline': date.Date('2003-02-16.22:50')},
1153                 {'title': 'issue two', 'status': '1', 'assignedto': '2',
1154                     'foo': date.Interval('1d'), 'priority': '3',
1155                     'deadline': date.Date('2003-01-01.00:00')},
1156                 {'title': 'issue three', 'status': '1', 'priority': '2',
1157                     'nosy': ['1','2'], 'deadline': date.Date('2003-02-18')},
1158                 {'title': 'non four', 'status': '3',
1159                     'foo': date.Interval('0:10'), 'priority': '2',
1160                     'nosy': ['1','2','3'], 'deadline': date.Date('2004-03-08'),
1161                     'files': [f]}):
1162             self.db.issue.create(**issue)
1163         self.db.commit()
1164         return self.iterSetup(classname)
1166     def testFilteringID(self):
1167         ae, filter, filter_iter = self.filteringSetup()
1168         for filt in filter, filter_iter:
1169             ae(filt(None, {'id': '1'}, ('+','id'), (None,None)), ['1'])
1170             ae(filt(None, {'id': '2'}, ('+','id'), (None,None)), ['2'])
1171             ae(filt(None, {'id': '100'}, ('+','id'), (None,None)), [])
1173     def testFilteringBoolean(self):
1174         ae, filter, filter_iter = self.filteringSetup('user')
1175         a = 'assignable'
1176         for filt in filter, filter_iter:
1177             ae(filt(None, {a: '1'}, ('+','id'), (None,None)), ['3','4'])
1178             ae(filt(None, {a: '0'}, ('+','id'), (None,None)), ['5'])
1179             ae(filt(None, {a: ['1']}, ('+','id'), (None,None)), ['3','4'])
1180             ae(filt(None, {a: ['0']}, ('+','id'), (None,None)), ['5'])
1181             ae(filt(None, {a: ['0','1']}, ('+','id'), (None,None)),
1182                 ['3','4','5'])
1183             ae(filt(None, {a: 'True'}, ('+','id'), (None,None)), ['3','4'])
1184             ae(filt(None, {a: 'False'}, ('+','id'), (None,None)), ['5'])
1185             ae(filt(None, {a: ['True']}, ('+','id'), (None,None)), ['3','4'])
1186             ae(filt(None, {a: ['False']}, ('+','id'), (None,None)), ['5'])
1187             ae(filt(None, {a: ['False','True']}, ('+','id'), (None,None)),
1188                 ['3','4','5'])
1189             ae(filt(None, {a: True}, ('+','id'), (None,None)), ['3','4'])
1190             ae(filt(None, {a: False}, ('+','id'), (None,None)), ['5'])
1191             ae(filt(None, {a: 1}, ('+','id'), (None,None)), ['3','4'])
1192             ae(filt(None, {a: 0}, ('+','id'), (None,None)), ['5'])
1193             ae(filt(None, {a: [1]}, ('+','id'), (None,None)), ['3','4'])
1194             ae(filt(None, {a: [0]}, ('+','id'), (None,None)), ['5'])
1195             ae(filt(None, {a: [0,1]}, ('+','id'), (None,None)), ['3','4','5'])
1196             ae(filt(None, {a: [True]}, ('+','id'), (None,None)), ['3','4'])
1197             ae(filt(None, {a: [False]}, ('+','id'), (None,None)), ['5'])
1198             ae(filt(None, {a: [False,True]}, ('+','id'), (None,None)),
1199                 ['3','4','5'])
1201     def testFilteringNumber(self):
1202         ae, filter, filter_iter = self.filteringSetup('user')
1203         for filt in filter, filter_iter:
1204             ae(filt(None, {'age': '1'}, ('+','id'), (None,None)), ['3'])
1205             ae(filt(None, {'age': '1.5'}, ('+','id'), (None,None)), ['4'])
1206             ae(filt(None, {'age': '2'}, ('+','id'), (None,None)), ['5'])
1207             ae(filt(None, {'age': ['1','2']}, ('+','id'), (None,None)),
1208                 ['3','5'])
1209             ae(filt(None, {'age': 2}, ('+','id'), (None,None)), ['5'])
1210             ae(filt(None, {'age': [1,2]}, ('+','id'), (None,None)), ['3','5'])
1212     def testFilteringString(self):
1213         ae, filter, filter_iter = self.filteringSetup()
1214         for filt in filter, filter_iter:
1215             ae(filt(None, {'title': ['one']}, ('+','id'), (None,None)), ['1'])
1216             ae(filt(None, {'title': ['issue one']}, ('+','id'), (None,None)),
1217                 ['1'])
1218             ae(filt(None, {'title': ['issue', 'one']}, ('+','id'), (None,None)),
1219                 ['1'])
1220             ae(filt(None, {'title': ['issue']}, ('+','id'), (None,None)),
1221                 ['1','2','3'])
1222             ae(filt(None, {'title': ['one', 'two']}, ('+','id'), (None,None)),
1223                 [])
1225     def testFilteringLink(self):
1226         ae, filter, filter_iter = self.filteringSetup()
1227         a = 'assignedto'
1228         grp = (None, None)
1229         for filt in filter, filter_iter:
1230             ae(filt(None, {'status': '1'}, ('+','id'), grp), ['2','3'])
1231             ae(filt(None, {a: '-1'}, ('+','id'), grp), ['3','4'])
1232             ae(filt(None, {a: None}, ('+','id'), grp), ['3','4'])
1233             ae(filt(None, {a: [None]}, ('+','id'), grp), ['3','4'])
1234             ae(filt(None, {a: ['-1', None]}, ('+','id'), grp), ['3','4'])
1235             ae(filt(None, {a: ['1', None]}, ('+','id'), grp), ['1', '3','4'])
1237     def testFilteringMultilinkAndGroup(self):
1238         """testFilteringMultilinkAndGroup:
1239         See roundup Bug 1541128: apparently grouping by something and
1240         searching a Multilink failed with MySQL 5.0
1241         """
1242         ae, filter, filter_iter = self.filteringSetup()
1243         for f in filter, filter_iter:
1244             ae(f(None, {'files': '1'}, ('-','activity'), ('+','status')), ['4'])
1246     def testFilteringRetired(self):
1247         ae, filter, filter_iter = self.filteringSetup()
1248         self.db.issue.retire('2')
1249         for f in filter, filter_iter:
1250             ae(f(None, {'status': '1'}, ('+','id'), (None,None)), ['3'])
1252     def testFilteringMultilink(self):
1253         ae, filter, filter_iter = self.filteringSetup()
1254         for filt in filter, filter_iter:
1255             ae(filt(None, {'nosy': '3'}, ('+','id'), (None,None)), ['4'])
1256             ae(filt(None, {'nosy': '-1'}, ('+','id'), (None,None)), ['1', '2'])
1257             ae(filt(None, {'nosy': ['1','2']}, ('+', 'status'),
1258                 ('-', 'deadline')), ['4', '3'])
1260     def testFilteringMany(self):
1261         ae, filter, filter_iter = self.filteringSetup()
1262         for f in filter, filter_iter:
1263             ae(f(None, {'nosy': '2', 'status': '1'}, ('+','id'), (None,None)),
1264                 ['3'])
1266     def testFilteringRangeBasic(self):
1267         ae, filter, filter_iter = self.filteringSetup()
1268         d = 'deadline'
1269         for f in filter, filter_iter:
1270             ae(f(None, {d: 'from 2003-02-10 to 2003-02-23'}), ['1','3'])
1271             ae(f(None, {d: '2003-02-10; 2003-02-23'}), ['1','3'])
1272             ae(f(None, {d: '; 2003-02-16'}), ['2'])
1274     def testFilteringRangeTwoSyntaxes(self):
1275         ae, filter, filter_iter = self.filteringSetup()
1276         for filt in filter, filter_iter:
1277             ae(filt(None, {'deadline': 'from 2003-02-16'}), ['1', '3', '4'])
1278             ae(filt(None, {'deadline': '2003-02-16;'}), ['1', '3', '4'])
1280     def testFilteringRangeYearMonthDay(self):
1281         ae, filter, filter_iter = self.filteringSetup()
1282         for filt in filter, filter_iter:
1283             ae(filt(None, {'deadline': '2002'}), [])
1284             ae(filt(None, {'deadline': '2003'}), ['1', '2', '3'])
1285             ae(filt(None, {'deadline': '2004'}), ['4'])
1286             ae(filt(None, {'deadline': '2003-02-16'}), ['1'])
1287             ae(filt(None, {'deadline': '2003-02-17'}), [])
1289     def testFilteringRangeMonths(self):
1290         ae, filter, filter_iter = self.filteringSetup()
1291         for month in range(1, 13):
1292             for n in range(1, month+1):
1293                 i = self.db.issue.create(title='%d.%d'%(month, n),
1294                     deadline=date.Date('2001-%02d-%02d.00:00'%(month, n)))
1295         self.db.commit()
1297         for month in range(1, 13):
1298             for filt in filter, filter_iter:
1299                 r = filt(None, dict(deadline='2001-%02d'%month))
1300                 assert len(r) == month, 'month %d != length %d'%(month, len(r))
1302     def testFilteringRangeInterval(self):
1303         ae, filter, filter_iter = self.filteringSetup()
1304         for filt in filter, filter_iter:
1305             ae(filt(None, {'foo': 'from 0:50 to 2:00'}), ['1'])
1306             ae(filt(None, {'foo': 'from 0:50 to 1d 2:00'}), ['1', '2'])
1307             ae(filt(None, {'foo': 'from 5:50'}), ['2'])
1308             ae(filt(None, {'foo': 'to 0:05'}), [])
1310     def testFilteringRangeGeekInterval(self):
1311         ae, filter, filter_iter = self.filteringSetup()
1312         for issue in (
1313                 { 'deadline': date.Date('. -2d')},
1314                 { 'deadline': date.Date('. -1d')},
1315                 { 'deadline': date.Date('. -8d')},
1316                 ):
1317             self.db.issue.create(**issue)
1318         for filt in filter, filter_iter:
1319             ae(filt(None, {'deadline': '-2d;'}), ['5', '6'])
1320             ae(filt(None, {'deadline': '-1d;'}), ['6'])
1321             ae(filt(None, {'deadline': '-1w;'}), ['5', '6'])
1323     def testFilteringIntervalSort(self):
1324         # 1: '1:10'
1325         # 2: '1d'
1326         # 3: None
1327         # 4: '0:10'
1328         ae, filter, filter_iter = self.filteringSetup()
1329         for filt in filter, filter_iter:
1330             # ascending should sort None, 1:10, 1d
1331             ae(filt(None, {}, ('+','foo'), (None,None)), ['3', '4', '1', '2'])
1332             # descending should sort 1d, 1:10, None
1333             ae(filt(None, {}, ('-','foo'), (None,None)), ['2', '1', '4', '3'])
1335     def testFilteringStringSort(self):
1336         # 1: 'issue one'
1337         # 2: 'issue two'
1338         # 3: 'issue three'
1339         # 4: 'non four'
1340         ae, filter, filter_iter = self.filteringSetup()
1341         for filt in filter, filter_iter:
1342             ae(filt(None, {}, ('+','title')), ['1', '3', '2', '4'])
1343             ae(filt(None, {}, ('-','title')), ['4', '2', '3', '1'])
1344         # Test string case: For now allow both, w/wo case matching.
1345         # 1: 'issue one'
1346         # 2: 'issue two'
1347         # 3: 'Issue three'
1348         # 4: 'non four'
1349         self.db.issue.set('3', title='Issue three')
1350         for filt in filter, filter_iter:
1351             ae(filt(None, {}, ('+','title')), ['1', '3', '2', '4'])
1352             ae(filt(None, {}, ('-','title')), ['4', '2', '3', '1'])
1353         # Obscure bug in anydbm backend trying to convert to number
1354         # 1: '1st issue'
1355         # 2: '2'
1356         # 3: 'Issue three'
1357         # 4: 'non four'
1358         self.db.issue.set('1', title='1st issue')
1359         self.db.issue.set('2', title='2')
1360         for filt in filter, filter_iter:
1361             ae(filt(None, {}, ('+','title')), ['1', '2', '3', '4'])
1362             ae(filt(None, {}, ('-','title')), ['4', '3', '2', '1'])
1364     def testFilteringMultilinkSort(self):
1365         # 1: []                 Reverse:  1: []
1366         # 2: []                           2: []
1367         # 3: ['admin','fred']             3: ['fred','admin']
1368         # 4: ['admin','bleep','fred']     4: ['fred','bleep','admin']
1369         # Note the sort order for the multilink doen't change when
1370         # reversing the sort direction due to the re-sorting of the
1371         # multilink!
1372         # Note that we don't test filter_iter here, Multilink sort-order
1373         # isn't defined for that.
1374         ae, filt, dummy = self.filteringSetup()
1375         ae(filt(None, {}, ('+','nosy'), (None,None)), ['1', '2', '4', '3'])
1376         ae(filt(None, {}, ('-','nosy'), (None,None)), ['4', '3', '1', '2'])
1378     def testFilteringMultilinkSortGroup(self):
1379         # 1: status: 2 "in-progress" nosy: []
1380         # 2: status: 1 "unread"      nosy: []
1381         # 3: status: 1 "unread"      nosy: ['admin','fred']
1382         # 4: status: 3 "testing"     nosy: ['admin','bleep','fred']
1383         # Note that we don't test filter_iter here, Multilink sort-order
1384         # isn't defined for that.
1385         ae, filt, dummy = self.filteringSetup()
1386         ae(filt(None, {}, ('+','nosy'), ('+','status')), ['1', '4', '2', '3'])
1387         ae(filt(None, {}, ('-','nosy'), ('+','status')), ['1', '4', '3', '2'])
1388         ae(filt(None, {}, ('+','nosy'), ('-','status')), ['2', '3', '4', '1'])
1389         ae(filt(None, {}, ('-','nosy'), ('-','status')), ['3', '2', '4', '1'])
1390         ae(filt(None, {}, ('+','status'), ('+','nosy')), ['1', '2', '4', '3'])
1391         ae(filt(None, {}, ('-','status'), ('+','nosy')), ['2', '1', '4', '3'])
1392         ae(filt(None, {}, ('+','status'), ('-','nosy')), ['4', '3', '1', '2'])
1393         ae(filt(None, {}, ('-','status'), ('-','nosy')), ['4', '3', '2', '1'])
1395     def testFilteringLinkSortGroup(self):
1396         # 1: status: 2 -> 'i', priority: 3 -> 1
1397         # 2: status: 1 -> 'u', priority: 3 -> 1
1398         # 3: status: 1 -> 'u', priority: 2 -> 3
1399         # 4: status: 3 -> 't', priority: 2 -> 3
1400         ae, filter, filter_iter = self.filteringSetup()
1401         for filt in filter, filter_iter:
1402             ae(filt(None, {}, ('+','status'), ('+','priority')),
1403                 ['1', '2', '4', '3'])
1404             ae(filt(None, {'priority':'2'}, ('+','status'), ('+','priority')),
1405                 ['4', '3'])
1406             ae(filt(None, {'priority.order':'3'}, ('+','status'),
1407                 ('+','priority')), ['4', '3'])
1408             ae(filt(None, {'priority':['2','3']}, ('+','priority'),
1409                 ('+','status')), ['1', '4', '2', '3'])
1410             ae(filt(None, {}, ('+','priority'), ('+','status')),
1411                 ['1', '4', '2', '3'])
1413     def testFilteringDateSort(self):
1414         # '1': '2003-02-16.22:50'
1415         # '2': '2003-01-01.00:00'
1416         # '3': '2003-02-18'
1417         # '4': '2004-03-08'
1418         ae, filter, filter_iter = self.filteringSetup()
1419         for f in filter, filter_iter:
1420             # ascending
1421             ae(f(None, {}, ('+','deadline'), (None,None)), ['2', '1', '3', '4'])
1422             # descending
1423             ae(f(None, {}, ('-','deadline'), (None,None)), ['4', '3', '1', '2'])
1425     def testFilteringDateSortPriorityGroup(self):
1426         # '1': '2003-02-16.22:50'  1 => 2
1427         # '2': '2003-01-01.00:00'  3 => 1
1428         # '3': '2003-02-18'        2 => 3
1429         # '4': '2004-03-08'        1 => 2
1430         ae, filter, filter_iter = self.filteringSetup()
1432         for filt in filter, filter_iter:
1433             # ascending
1434             ae(filt(None, {}, ('+','deadline'), ('+','priority')),
1435                 ['2', '1', '3', '4'])
1436             ae(filt(None, {}, ('-','deadline'), ('+','priority')),
1437                 ['1', '2', '4', '3'])
1438             # descending
1439             ae(filt(None, {}, ('+','deadline'), ('-','priority')),
1440                 ['3', '4', '2', '1'])
1441             ae(filt(None, {}, ('-','deadline'), ('-','priority')),
1442                 ['4', '3', '1', '2'])
1444     def testFilteringTransitiveLinkUser(self):
1445         ae, filter, filter_iter = self.filteringSetupTransitiveSearch('user')
1446         for f in filter, filter_iter:
1447             ae(f(None, {'supervisor.username': 'ceo'}, ('+','username')),
1448                 ['4', '5'])
1449             ae(f(None, {'supervisor.supervisor.username': 'ceo'},
1450                 ('+','username')), ['6', '7', '8', '9', '10'])
1451             ae(f(None, {'supervisor.supervisor': '3'}, ('+','username')),
1452                 ['6', '7', '8', '9', '10'])
1453             ae(f(None, {'supervisor.supervisor.id': '3'}, ('+','username')),
1454                 ['6', '7', '8', '9', '10'])
1455             ae(f(None, {'supervisor.username': 'grouplead1'}, ('+','username')),
1456                 ['6', '7'])
1457             ae(f(None, {'supervisor.username': 'grouplead2'}, ('+','username')),
1458                 ['8', '9', '10'])
1459             ae(f(None, {'supervisor.username': 'grouplead2',
1460                 'supervisor.supervisor.username': 'ceo'}, ('+','username')),
1461                 ['8', '9', '10'])
1462             ae(f(None, {'supervisor.supervisor': '3', 'supervisor': '4'},
1463                 ('+','username')), ['6', '7'])
1465     def testFilteringTransitiveLinkSort(self):
1466         ae, filter, filter_iter = self.filteringSetupTransitiveSearch()
1467         ae, ufilter, ufilter_iter = self.iterSetup('user')
1468         # Need to make ceo his own (and first two users') supervisor,
1469         # otherwise we will depend on sorting order of NULL values.
1470         # Leave that to a separate test.
1471         self.db.user.set('1', supervisor = '3')
1472         self.db.user.set('2', supervisor = '3')
1473         self.db.user.set('3', supervisor = '3')
1474         for ufilt in ufilter, ufilter_iter:
1475             ae(ufilt(None, {'supervisor':'3'}, []), ['1', '2', '3', '4', '5'])
1476             ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1477                 ('+','supervisor.supervisor'), ('+','supervisor'),
1478                 ('+','username')]),
1479                 ['1', '3', '2', '4', '5', '6', '7', '8', '9', '10'])
1480             ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1481                 ('-','supervisor.supervisor'), ('-','supervisor'),
1482                 ('+','username')]),
1483                 ['8', '9', '10', '6', '7', '1', '3', '2', '4', '5'])
1484         for f in filter, filter_iter:
1485             ae(f(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1486                 ('+','assignedto.supervisor.supervisor'),
1487                 ('+','assignedto.supervisor'), ('+','assignedto')]),
1488                 ['1', '2', '3', '4', '5', '6', '7', '8'])
1489             ae(f(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1490                 ('+','assignedto.supervisor.supervisor'),
1491                 ('-','assignedto.supervisor'), ('+','assignedto')]),
1492                 ['4', '5', '6', '7', '8', '1', '2', '3'])
1493             ae(f(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1494                 ('+','assignedto.supervisor.supervisor'),
1495                 ('+','assignedto.supervisor'), ('+','assignedto'),
1496                 ('-','status')]),
1497                 ['2', '1', '3', '4', '5', '6', '8', '7'])
1498             ae(f(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1499                 ('+','assignedto.supervisor.supervisor'),
1500                 ('+','assignedto.supervisor'), ('+','assignedto'),
1501                 ('+','status')]),
1502                 ['1', '2', '3', '4', '5', '7', '6', '8'])
1503             ae(f(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1504                 ('+','assignedto.supervisor.supervisor'),
1505                 ('-','assignedto.supervisor'), ('+','assignedto'),
1506                 ('+','status')]), ['4', '5', '7', '6', '8', '1', '2', '3'])
1507             ae(f(None, {'assignedto':['6','7','8','9','10']},
1508                 [('+','assignedto.supervisor.supervisor.supervisor'),
1509                 ('+','assignedto.supervisor.supervisor'),
1510                 ('-','assignedto.supervisor'), ('+','assignedto'),
1511                 ('+','status')]), ['4', '5', '7', '6', '8', '1', '2', '3'])
1512             ae(f(None, {'assignedto':['6','7','8','9']},
1513                 [('+','assignedto.supervisor.supervisor.supervisor'),
1514                 ('+','assignedto.supervisor.supervisor'),
1515                 ('-','assignedto.supervisor'), ('+','assignedto'),
1516                 ('+','status')]), ['4', '5', '1', '2', '3'])
1518     def testFilteringTransitiveLinkSortNull(self):
1519         """Check sorting of NULL values"""
1520         ae, filter, filter_iter = self.filteringSetupTransitiveSearch()
1521         ae, ufilter, ufilter_iter = self.iterSetup('user')
1522         for ufilt in ufilter, ufilter_iter:
1523             ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1524                 ('+','supervisor.supervisor'), ('+','supervisor'),
1525                 ('+','username')]),
1526                 ['1', '3', '2', '4', '5', '6', '7', '8', '9', '10'])
1527             ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1528                 ('-','supervisor.supervisor'), ('-','supervisor'),
1529                 ('+','username')]),
1530                 ['8', '9', '10', '6', '7', '4', '5', '1', '3', '2'])
1531         for f in filter, filter_iter:
1532             ae(f(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1533                 ('+','assignedto.supervisor.supervisor'),
1534                 ('+','assignedto.supervisor'), ('+','assignedto')]),
1535                 ['1', '2', '3', '4', '5', '6', '7', '8'])
1536             ae(f(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1537                 ('+','assignedto.supervisor.supervisor'),
1538                 ('-','assignedto.supervisor'), ('+','assignedto')]),
1539                 ['4', '5', '6', '7', '8', '1', '2', '3'])
1541     def testFilteringTransitiveLinkIssue(self):
1542         ae, filter, filter_iter = self.filteringSetupTransitiveSearch()
1543         for filt in filter, filter_iter:
1544             ae(filt(None, {'assignedto.supervisor.username': 'grouplead1'},
1545                 ('+','id')), ['1', '2', '3'])
1546             ae(filt(None, {'assignedto.supervisor.username': 'grouplead2'},
1547                 ('+','id')), ['4', '5', '6', '7', '8'])
1548             ae(filt(None, {'assignedto.supervisor.username': 'grouplead2',
1549                            'status': '1'}, ('+','id')), ['4', '6', '8'])
1550             ae(filt(None, {'assignedto.supervisor.username': 'grouplead2',
1551                            'status': '2'}, ('+','id')), ['5', '7'])
1552             ae(filt(None, {'assignedto.supervisor.username': ['grouplead2'],
1553                            'status': '2'}, ('+','id')), ['5', '7'])
1554             ae(filt(None, {'assignedto.supervisor': ['4', '5'], 'status': '2'},
1555                 ('+','id')), ['1', '3', '5', '7'])
1557     def testFilteringTransitiveMultilink(self):
1558         ae, filter, filter_iter = self.filteringSetupTransitiveSearch()
1559         for filt in filter, filter_iter:
1560             ae(filt(None, {'messages.author.username': 'grouplead1'},
1561                 ('+','id')), [])
1562             ae(filt(None, {'messages.author': '6'},
1563                 ('+','id')), ['1', '2'])
1564             ae(filt(None, {'messages.author.id': '6'},
1565                 ('+','id')), ['1', '2'])
1566             ae(filt(None, {'messages.author.username': 'worker1'},
1567                 ('+','id')), ['1', '2'])
1568             ae(filt(None, {'messages.author': '10'},
1569                 ('+','id')), ['6', '7', '8'])
1570             ae(filt(None, {'messages.author': '9'},
1571                 ('+','id')), ['5', '8'])
1572             ae(filt(None, {'messages.author': ['9', '10']},
1573                 ('+','id')), ['5', '6', '7', '8'])
1574             ae(filt(None, {'messages.author': ['8', '9']},
1575                 ('+','id')), ['4', '5', '8'])
1576             ae(filt(None, {'messages.author': ['8', '9'], 'status' : '1'},
1577                 ('+','id')), ['4', '8'])
1578             ae(filt(None, {'messages.author': ['8', '9'], 'status' : '2'},
1579                 ('+','id')), ['5'])
1580             ae(filt(None, {'messages.author': ['8', '9', '10'],
1581                 'messages.date': '2006-01-22.21:00;2006-01-23'}, ('+','id')),
1582                 ['6', '7', '8'])
1583             ae(filt(None, {'nosy.supervisor.username': 'ceo'},
1584                 ('+','id')), ['1', '2'])
1585             ae(filt(None, {'messages.author': ['6', '9']},
1586                 ('+','id')), ['1', '2', '5', '8'])
1587             ae(filt(None, {'messages': ['5', '7']},
1588                 ('+','id')), ['3', '5', '8'])
1589             ae(filt(None, {'messages.author': ['6', '9'],
1590                 'messages': ['5', '7']}, ('+','id')), ['5', '8'])
1592     def testFilteringTransitiveMultilinkSort(self):
1593         # Note that we don't test filter_iter here, Multilink sort-order
1594         # isn't defined for that.
1595         ae, filt, dummy = self.filteringSetupTransitiveSearch()
1596         ae(filt(None, {}, [('+','messages.author')]),
1597             ['1', '2', '3', '4', '5', '8', '6', '7'])
1598         ae(filt(None, {}, [('-','messages.author')]),
1599             ['8', '6', '7', '5', '4', '3', '1', '2'])
1600         ae(filt(None, {}, [('+','messages.date')]),
1601             ['6', '7', '8', '5', '4', '3', '1', '2'])
1602         ae(filt(None, {}, [('-','messages.date')]),
1603             ['1', '2', '3', '4', '8', '5', '6', '7'])
1604         ae(filt(None, {}, [('+','messages.author'),('+','messages.date')]),
1605             ['1', '2', '3', '4', '5', '8', '6', '7'])
1606         ae(filt(None, {}, [('-','messages.author'),('+','messages.date')]),
1607             ['8', '6', '7', '5', '4', '3', '1', '2'])
1608         ae(filt(None, {}, [('+','messages.author'),('-','messages.date')]),
1609             ['1', '2', '3', '4', '5', '8', '6', '7'])
1610         ae(filt(None, {}, [('-','messages.author'),('-','messages.date')]),
1611             ['8', '6', '7', '5', '4', '3', '1', '2'])
1612         ae(filt(None, {}, [('+','messages.author'),('+','assignedto')]),
1613             ['1', '2', '3', '4', '5', '8', '6', '7'])
1614         ae(filt(None, {}, [('+','messages.author'),
1615             ('-','assignedto.supervisor'),('-','assignedto')]),
1616             ['1', '2', '3', '4', '5', '8', '6', '7'])
1617         ae(filt(None, {},
1618             [('+','messages.author.supervisor.supervisor.supervisor'),
1619             ('+','messages.author.supervisor.supervisor'),
1620             ('+','messages.author.supervisor'), ('+','messages.author')]),
1621             ['1', '2', '3', '4', '5', '6', '7', '8'])
1622         self.db.user.setorderprop('age')
1623         self.db.msg.setorderprop('date')
1624         ae(filt(None, {}, [('+','messages'), ('+','messages.author')]),
1625             ['6', '7', '8', '5', '4', '3', '1', '2'])
1626         ae(filt(None, {}, [('+','messages.author'), ('+','messages')]),
1627             ['6', '7', '8', '5', '4', '3', '1', '2'])
1628         self.db.msg.setorderprop('author')
1629         # Orderprop is a Link/Multilink:
1630         # messages are sorted by orderprop().labelprop(), i.e. by
1631         # author.username, *not* by author.orderprop() (author.age)!
1632         ae(filt(None, {}, [('+','messages')]),
1633             ['1', '2', '3', '4', '5', '8', '6', '7'])
1634         ae(filt(None, {}, [('+','messages.author'), ('+','messages')]),
1635             ['6', '7', '8', '5', '4', '3', '1', '2'])
1636         # The following will sort by
1637         # author.supervisor.username and then by
1638         # author.username
1639         # I've resited the tempation to implement recursive orderprop
1640         # here: There could even be loops if several classes specify a
1641         # Link or Multilink as the orderprop...
1642         # msg: 4: worker1 (id  5) : grouplead1 (id 4) ceo (id 3)
1643         # msg: 5: worker2 (id  7) : grouplead1 (id 4) ceo (id 3)
1644         # msg: 6: worker3 (id  8) : grouplead2 (id 5) ceo (id 3)
1645         # msg: 7: worker4 (id  9) : grouplead2 (id 5) ceo (id 3)
1646         # msg: 8: worker5 (id 10) : grouplead2 (id 5) ceo (id 3)
1647         # issue 1: messages 4   sortkey:[[grouplead1], [worker1], 1]
1648         # issue 2: messages 4   sortkey:[[grouplead1], [worker1], 2]
1649         # issue 3: messages 5   sortkey:[[grouplead1], [worker2], 3]
1650         # issue 4: messages 6   sortkey:[[grouplead2], [worker3], 4]
1651         # issue 5: messages 7   sortkey:[[grouplead2], [worker4], 5]
1652         # issue 6: messages 8   sortkey:[[grouplead2], [worker5], 6]
1653         # issue 7: messages 8   sortkey:[[grouplead2], [worker5], 7]
1654         # issue 8: messages 7,8 sortkey:[[grouplead2, grouplead2], ...]
1655         self.db.user.setorderprop('supervisor')
1656         ae(filt(None, {}, [('+','messages.author'), ('-','messages')]),
1657             ['3', '1', '2', '6', '7', '5', '4', '8'])
1659     def testFilteringSortId(self):
1660         ae, filter, filter_iter = self.filteringSetupTransitiveSearch('user')
1661         for filt in filter, filter_iter:
1662             ae(filt(None, {}, ('+','id')),
1663                 ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])
1665 # XXX add sorting tests for other types
1667     # nuke and re-create db for restore
1668     def nukeAndCreate(self):
1669         # shut down this db and nuke it
1670         self.db.close()
1671         self.nuke_database()
1673         # open a new, empty database
1674         os.makedirs(config.DATABASE + '/files')
1675         self.db = self.module.Database(config, 'admin')
1676         setupSchema(self.db, 0, self.module)
1678     def testImportExport(self):
1679         # use the filtering setup to create a bunch of items
1680         ae, dummy1, dummy2 = self.filteringSetup()
1681         # Get some stuff into the journal for testing import/export of
1682         # journal data:
1683         self.db.user.set('4', password = password.Password('xyzzy'))
1684         self.db.user.set('4', age = 3)
1685         self.db.user.set('4', assignable = True)
1686         self.db.issue.set('1', title = 'i1', status = '3')
1687         self.db.issue.set('1', deadline = date.Date('2007'))
1688         self.db.issue.set('1', foo = date.Interval('1:20'))
1689         p = self.db.priority.create(name = 'some_prio_without_order')
1690         self.db.commit()
1691         self.db.user.set('4', password = password.Password('123xyzzy'))
1692         self.db.user.set('4', assignable = False)
1693         self.db.priority.set(p, order = '4711')
1694         self.db.commit()
1696         self.db.user.retire('3')
1697         self.db.issue.retire('2')
1699         # grab snapshot of the current database
1700         orig = {}
1701         origj = {}
1702         for cn,klass in self.db.classes.items():
1703             cl = orig[cn] = {}
1704             jn = origj[cn] = {}
1705             for id in klass.list():
1706                 it = cl[id] = {}
1707                 jn[id] = self.db.getjournal(cn, id)
1708                 for name in klass.getprops().keys():
1709                     it[name] = klass.get(id, name)
1711         os.mkdir('_test_export')
1712         try:
1713             # grab the export
1714             export = {}
1715             journals = {}
1716             for cn,klass in self.db.classes.items():
1717                 names = klass.export_propnames()
1718                 cl = export[cn] = [names+['is retired']]
1719                 for id in klass.getnodeids():
1720                     cl.append(klass.export_list(names, id))
1721                     if hasattr(klass, 'export_files'):
1722                         klass.export_files('_test_export', id)
1723                 journals[cn] = klass.export_journals()
1725             self.nukeAndCreate()
1727             # import
1728             for cn, items in export.items():
1729                 klass = self.db.classes[cn]
1730                 names = items[0]
1731                 maxid = 1
1732                 for itemprops in items[1:]:
1733                     id = int(klass.import_list(names, itemprops))
1734                     if hasattr(klass, 'import_files'):
1735                         klass.import_files('_test_export', str(id))
1736                     maxid = max(maxid, id)
1737                 self.db.setid(cn, str(maxid+1))
1738                 klass.import_journals(journals[cn])
1739             # This is needed, otherwise journals won't be there for anydbm
1740             self.db.commit()
1741         finally:
1742             shutil.rmtree('_test_export')
1744         # compare with snapshot of the database
1745         for cn, items in orig.iteritems():
1746             klass = self.db.classes[cn]
1747             propdefs = klass.getprops(1)
1748             # ensure retired items are retired :)
1749             l = items.keys(); l.sort()
1750             m = klass.list(); m.sort()
1751             ae(l, m, '%s id list wrong %r vs. %r'%(cn, l, m))
1752             for id, props in items.items():
1753                 for name, value in props.items():
1754                     l = klass.get(id, name)
1755                     if isinstance(value, type([])):
1756                         value.sort()
1757                         l.sort()
1758                     try:
1759                         ae(l, value)
1760                     except AssertionError:
1761                         if not isinstance(propdefs[name], Date):
1762                             raise
1763                         # don't get hung up on rounding errors
1764                         assert not l.__cmp__(value, int_seconds=1)
1765         for jc, items in origj.iteritems():
1766             for id, oj in items.iteritems():
1767                 rj = self.db.getjournal(jc, id)
1768                 # Both mysql and postgresql have some minor issues with
1769                 # rounded seconds on export/import, so we compare only
1770                 # the integer part.
1771                 for j in oj:
1772                     j[1].second = float(int(j[1].second))
1773                 for j in rj:
1774                     j[1].second = float(int(j[1].second))
1775                 oj.sort()
1776                 rj.sort()
1777                 ae(oj, rj)
1779         # make sure the retired items are actually imported
1780         ae(self.db.user.get('4', 'username'), 'blop')
1781         ae(self.db.issue.get('2', 'title'), 'issue two')
1783         # make sure id counters are set correctly
1784         maxid = max([int(id) for id in self.db.user.list()])
1785         newid = self.db.user.create(username='testing')
1786         assert newid > maxid
1788     # test import/export via admin interface
1789     def testAdminImportExport(self):
1790         import roundup.admin
1791         import csv
1792         # use the filtering setup to create a bunch of items
1793         ae, dummy1, dummy2 = self.filteringSetup()
1794         # create large field
1795         self.db.priority.create(name = 'X' * 500)
1796         self.db.config.CSV_FIELD_SIZE = 400
1797         self.db.commit()
1798         output = []
1799         # ugly hack to get stderr output and disable stdout output
1800         # during regression test. Depends on roundup.admin not using
1801         # anything but stdout/stderr from sys (which is currently the
1802         # case)
1803         def stderrwrite(s):
1804             output.append(s)
1805         roundup.admin.sys = MockNull ()
1806         try:
1807             roundup.admin.sys.stderr.write = stderrwrite
1808             tool = roundup.admin.AdminTool()
1809             home = '.'
1810             tool.tracker_home = home
1811             tool.db = self.db
1812             tool.verbose = False
1813             tool.do_export (['_test_export'])
1814             self.assertEqual(len(output), 2)
1815             self.assertEqual(output [1], '\n')
1816             self.failUnless(output [0].startswith
1817                 ('Warning: config csv_field_size should be at least'))
1818             self.failUnless(int(output[0].split()[-1]) > 500)
1820             if hasattr(roundup.admin.csv, 'field_size_limit'):
1821                 self.nukeAndCreate()
1822                 self.db.config.CSV_FIELD_SIZE = 400
1823                 tool = roundup.admin.AdminTool()
1824                 tool.tracker_home = home
1825                 tool.db = self.db
1826                 tool.verbose = False
1827                 self.assertRaises(csv.Error, tool.do_import, ['_test_export'])
1829             self.nukeAndCreate()
1830             self.db.config.CSV_FIELD_SIZE = 3200
1831             tool = roundup.admin.AdminTool()
1832             tool.tracker_home = home
1833             tool.db = self.db
1834             tool.verbose = False
1835             tool.do_import(['_test_export'])
1836         finally:
1837             roundup.admin.sys = sys
1838             shutil.rmtree('_test_export')
1840     def testAddProperty(self):
1841         self.db.issue.create(title="spam", status='1')
1842         self.db.commit()
1844         self.db.issue.addprop(fixer=Link("user"))
1845         # force any post-init stuff to happen
1846         self.db.post_init()
1847         props = self.db.issue.getprops()
1848         keys = props.keys()
1849         keys.sort()
1850         self.assertEqual(keys, ['activity', 'actor', 'assignedto', 'creation',
1851             'creator', 'deadline', 'feedback', 'files', 'fixer', 'foo', 'id', 'messages',
1852             'nosy', 'priority', 'spam', 'status', 'superseder', 'title'])
1853         self.assertEqual(self.db.issue.get('1', "fixer"), None)
1855     def testRemoveProperty(self):
1856         self.db.issue.create(title="spam", status='1')
1857         self.db.commit()
1859         del self.db.issue.properties['title']
1860         self.db.post_init()
1861         props = self.db.issue.getprops()
1862         keys = props.keys()
1863         keys.sort()
1864         self.assertEqual(keys, ['activity', 'actor', 'assignedto', 'creation',
1865             'creator', 'deadline', 'feedback', 'files', 'foo', 'id', 'messages',
1866             'nosy', 'priority', 'spam', 'status', 'superseder'])
1867         self.assertEqual(self.db.issue.list(), ['1'])
1869     def testAddRemoveProperty(self):
1870         self.db.issue.create(title="spam", status='1')
1871         self.db.commit()
1873         self.db.issue.addprop(fixer=Link("user"))
1874         del self.db.issue.properties['title']
1875         self.db.post_init()
1876         props = self.db.issue.getprops()
1877         keys = props.keys()
1878         keys.sort()
1879         self.assertEqual(keys, ['activity', 'actor', 'assignedto', 'creation',
1880             'creator', 'deadline', 'feedback', 'files', 'fixer', 'foo', 'id',
1881             'messages', 'nosy', 'priority', 'spam', 'status', 'superseder'])
1882         self.assertEqual(self.db.issue.list(), ['1'])
1884     def testNosyMail(self) :
1885         """Creates one issue with two attachments, one smaller and one larger
1886            than the set max_attachment_size.
1887         """
1888         old_translate_ = roundupdb._
1889         roundupdb._ = i18n.get_translation(language='C').gettext
1890         db = self.db
1891         db.config.NOSY_MAX_ATTACHMENT_SIZE = 4096
1892         res = dict(mail_to = None, mail_msg = None)
1893         def dummy_snd(s, to, msg, res=res) :
1894             res["mail_to"], res["mail_msg"] = to, msg
1895         backup, Mailer.smtp_send = Mailer.smtp_send, dummy_snd
1896         try :
1897             f1 = db.file.create(name="test1.txt", content="x" * 20)
1898             f2 = db.file.create(name="test2.txt", content="y" * 5000)
1899             m  = db.msg.create(content="one two", author="admin",
1900                 files = [f1, f2])
1901             i  = db.issue.create(title='spam', files = [f1, f2],
1902                 messages = [m], nosy = [db.user.lookup("fred")])
1904             db.issue.nosymessage(i, m, {})
1905             mail_msg = str(res["mail_msg"])
1906             self.assertEqual(res["mail_to"], ["fred@example.com"])
1907             self.assert_("From: admin" in mail_msg)
1908             self.assert_("Subject: [issue1] spam" in mail_msg)
1909             self.assert_("New submission from admin" in mail_msg)
1910             self.assert_("one two" in mail_msg)
1911             self.assert_("File 'test1.txt' not attached" not in mail_msg)
1912             self.assert_(base64.encodestring("xxx").rstrip() in mail_msg)
1913             self.assert_("File 'test2.txt' not attached" in mail_msg)
1914             self.assert_(base64.encodestring("yyy").rstrip() not in mail_msg)
1915         finally :
1916             roundupdb._ = old_translate_
1917             Mailer.smtp_send = backup
1919 class ROTest(MyTestCase):
1920     def setUp(self):
1921         # remove previous test, ignore errors
1922         if os.path.exists(config.DATABASE):
1923             shutil.rmtree(config.DATABASE)
1924         os.makedirs(config.DATABASE + '/files')
1925         self.db = self.module.Database(config, 'admin')
1926         setupSchema(self.db, 1, self.module)
1927         self.db.close()
1929         self.db = self.module.Database(config)
1930         setupSchema(self.db, 0, self.module)
1932     def testExceptions(self):
1933         # this tests the exceptions that should be raised
1934         ar = self.assertRaises
1936         # this tests the exceptions that should be raised
1937         ar(DatabaseError, self.db.status.create, name="foo")
1938         ar(DatabaseError, self.db.status.set, '1', name="foo")
1939         ar(DatabaseError, self.db.status.retire, '1')
1942 class SchemaTest(MyTestCase):
1943     def setUp(self):
1944         # remove previous test, ignore errors
1945         if os.path.exists(config.DATABASE):
1946             shutil.rmtree(config.DATABASE)
1947         os.makedirs(config.DATABASE + '/files')
1949     def test_reservedProperties(self):
1950         self.open_database()
1951         self.assertRaises(ValueError, self.module.Class, self.db, "a",
1952             creation=String())
1953         self.assertRaises(ValueError, self.module.Class, self.db, "a",
1954             activity=String())
1955         self.assertRaises(ValueError, self.module.Class, self.db, "a",
1956             creator=String())
1957         self.assertRaises(ValueError, self.module.Class, self.db, "a",
1958             actor=String())
1960     def init_a(self):
1961         self.open_database()
1962         a = self.module.Class(self.db, "a", name=String())
1963         a.setkey("name")
1964         self.db.post_init()
1966     def test_fileClassProps(self):
1967         self.open_database()
1968         a = self.module.FileClass(self.db, 'a')
1969         l = a.getprops().keys()
1970         l.sort()
1971         self.assert_(l, ['activity', 'actor', 'content', 'created',
1972             'creation', 'type'])
1974     def init_ab(self):
1975         self.open_database()
1976         a = self.module.Class(self.db, "a", name=String())
1977         a.setkey("name")
1978         b = self.module.Class(self.db, "b", name=String(),
1979             fooz=Multilink('a'))
1980         b.setkey("name")
1981         self.db.post_init()
1983     def test_addNewClass(self):
1984         self.init_a()
1986         self.assertRaises(ValueError, self.module.Class, self.db, "a",
1987             name=String())
1989         aid = self.db.a.create(name='apple')
1990         self.db.commit(); self.db.close()
1992         # add a new class to the schema and check creation of new items
1993         # (and existence of old ones)
1994         self.init_ab()
1995         bid = self.db.b.create(name='bear', fooz=[aid])
1996         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
1997         self.db.commit()
1998         self.db.close()
2000         # now check we can recall the added class' items
2001         self.init_ab()
2002         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
2003         self.assertEqual(self.db.a.lookup('apple'), aid)
2004         self.assertEqual(self.db.b.get(bid, 'name'), 'bear')
2005         self.assertEqual(self.db.b.get(bid, 'fooz'), [aid])
2006         self.assertEqual(self.db.b.lookup('bear'), bid)
2008         # confirm journal's ok
2009         self.db.getjournal('a', aid)
2010         self.db.getjournal('b', bid)
2012     def init_amod(self):
2013         self.open_database()
2014         a = self.module.Class(self.db, "a", name=String(), newstr=String(),
2015             newint=Interval(), newnum=Number(), newbool=Boolean(),
2016             newdate=Date())
2017         a.setkey("name")
2018         b = self.module.Class(self.db, "b", name=String())
2019         b.setkey("name")
2020         self.db.post_init()
2022     def test_modifyClass(self):
2023         self.init_ab()
2025         # add item to user and issue class
2026         aid = self.db.a.create(name='apple')
2027         bid = self.db.b.create(name='bear')
2028         self.db.commit(); self.db.close()
2030         # modify "a" schema
2031         self.init_amod()
2032         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
2033         self.assertEqual(self.db.a.get(aid, 'newstr'), None)
2034         self.assertEqual(self.db.a.get(aid, 'newint'), None)
2035         # hack - metakit can't return None for missing values, and we're not
2036         # really checking for that behavior here anyway
2037         self.assert_(not self.db.a.get(aid, 'newnum'))
2038         self.assert_(not self.db.a.get(aid, 'newbool'))
2039         self.assertEqual(self.db.a.get(aid, 'newdate'), None)
2040         self.assertEqual(self.db.b.get(aid, 'name'), 'bear')
2041         aid2 = self.db.a.create(name='aardvark', newstr='booz')
2042         self.db.commit(); self.db.close()
2044         # test
2045         self.init_amod()
2046         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
2047         self.assertEqual(self.db.a.get(aid, 'newstr'), None)
2048         self.assertEqual(self.db.b.get(aid, 'name'), 'bear')
2049         self.assertEqual(self.db.a.get(aid2, 'name'), 'aardvark')
2050         self.assertEqual(self.db.a.get(aid2, 'newstr'), 'booz')
2052         # confirm journal's ok
2053         self.db.getjournal('a', aid)
2054         self.db.getjournal('a', aid2)
2056     def init_amodkey(self):
2057         self.open_database()
2058         a = self.module.Class(self.db, "a", name=String(), newstr=String())
2059         a.setkey("newstr")
2060         b = self.module.Class(self.db, "b", name=String())
2061         b.setkey("name")
2062         self.db.post_init()
2064     def test_changeClassKey(self):
2065         self.init_amod()
2066         aid = self.db.a.create(name='apple')
2067         self.assertEqual(self.db.a.lookup('apple'), aid)
2068         self.db.commit(); self.db.close()
2070         # change the key to newstr on a
2071         self.init_amodkey()
2072         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
2073         self.assertEqual(self.db.a.get(aid, 'newstr'), None)
2074         self.assertRaises(KeyError, self.db.a.lookup, 'apple')
2075         aid2 = self.db.a.create(name='aardvark', newstr='booz')
2076         self.db.commit(); self.db.close()
2078         # check
2079         self.init_amodkey()
2080         self.assertEqual(self.db.a.lookup('booz'), aid2)
2082         # confirm journal's ok
2083         self.db.getjournal('a', aid)
2085     def test_removeClassKey(self):
2086         self.init_amod()
2087         aid = self.db.a.create(name='apple')
2088         self.assertEqual(self.db.a.lookup('apple'), aid)
2089         self.db.commit(); self.db.close()
2091         self.db = self.module.Database(config, 'admin')
2092         a = self.module.Class(self.db, "a", name=String(), newstr=String())
2093         self.db.post_init()
2095         aid2 = self.db.a.create(name='apple', newstr='booz')
2096         self.db.commit()
2099     def init_amodml(self):
2100         self.open_database()
2101         a = self.module.Class(self.db, "a", name=String(),
2102             newml=Multilink('a'))
2103         a.setkey('name')
2104         self.db.post_init()
2106     def test_makeNewMultilink(self):
2107         self.init_a()
2108         aid = self.db.a.create(name='apple')
2109         self.assertEqual(self.db.a.lookup('apple'), aid)
2110         self.db.commit(); self.db.close()
2112         # add a multilink prop
2113         self.init_amodml()
2114         bid = self.db.a.create(name='bear', newml=[aid])
2115         self.assertEqual(self.db.a.find(newml=aid), [bid])
2116         self.assertEqual(self.db.a.lookup('apple'), aid)
2117         self.db.commit(); self.db.close()
2119         # check
2120         self.init_amodml()
2121         self.assertEqual(self.db.a.find(newml=aid), [bid])
2122         self.assertEqual(self.db.a.lookup('apple'), aid)
2123         self.assertEqual(self.db.a.lookup('bear'), bid)
2125         # confirm journal's ok
2126         self.db.getjournal('a', aid)
2127         self.db.getjournal('a', bid)
2129     def test_removeMultilink(self):
2130         # add a multilink prop
2131         self.init_amodml()
2132         aid = self.db.a.create(name='apple')
2133         bid = self.db.a.create(name='bear', newml=[aid])
2134         self.assertEqual(self.db.a.find(newml=aid), [bid])
2135         self.assertEqual(self.db.a.lookup('apple'), aid)
2136         self.assertEqual(self.db.a.lookup('bear'), bid)
2137         self.db.commit(); self.db.close()
2139         # remove the multilink
2140         self.init_a()
2141         self.assertEqual(self.db.a.lookup('apple'), aid)
2142         self.assertEqual(self.db.a.lookup('bear'), bid)
2144         # confirm journal's ok
2145         self.db.getjournal('a', aid)
2146         self.db.getjournal('a', bid)
2148     def test_removeClass(self):
2149         self.init_ab()
2150         aid = self.db.a.create(name='apple')
2151         bid = self.db.b.create(name='bear')
2152         self.db.commit(); self.db.close()
2154         # drop the b class
2155         self.init_a()
2156         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
2157         self.assertEqual(self.db.a.lookup('apple'), aid)
2158         self.db.commit(); self.db.close()
2160         # now check we can recall the added class' items
2161         self.init_a()
2162         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
2163         self.assertEqual(self.db.a.lookup('apple'), aid)
2165         # confirm journal's ok
2166         self.db.getjournal('a', aid)
2168 class RDBMSTest:
2169     """ tests specific to RDBMS backends """
2170     def test_indexTest(self):
2171         self.assertEqual(self.db.sql_index_exists('_issue', '_issue_id_idx'), 1)
2172         self.assertEqual(self.db.sql_index_exists('_issue', '_issue_x_idx'), 0)
2174 class FilterCacheTest(commonDBTest):
2175     def testFilteringTransitiveLinkCache(self):
2176         ae, filter, filter_iter = self.filteringSetupTransitiveSearch()
2177         ae, ufilter, ufilter_iter = self.iterSetup('user')
2178         # Need to make ceo his own (and first two users') supervisor
2179         self.db.user.set('1', supervisor = '3')
2180         self.db.user.set('2', supervisor = '3')
2181         self.db.user.set('3', supervisor = '3')
2182         # test bool value
2183         self.db.user.set('4', assignable = True)
2184         self.db.user.set('3', assignable = False)
2185         filt = self.db.issue.filter_iter
2186         ufilt = self.db.user.filter_iter
2187         user_result = \
2188             {  '1' : {'username': 'admin', 'assignable': None,
2189                       'supervisor': '3', 'realname': None, 'roles': 'Admin',
2190                       'creator': '1', 'age': None, 'actor': '1',
2191                       'address': None}
2192             ,  '2' : {'username': 'fred', 'assignable': None,
2193                       'supervisor': '3', 'realname': None, 'roles': 'User',
2194                       'creator': '1', 'age': None, 'actor': '1',
2195                       'address': 'fred@example.com'}
2196             ,  '3' : {'username': 'ceo', 'assignable': False,
2197                       'supervisor': '3', 'realname': None, 'roles': None,
2198                       'creator': '1', 'age': 129.0, 'actor': '1',
2199                       'address': None}
2200             ,  '4' : {'username': 'grouplead1', 'assignable': True,
2201                       'supervisor': '3', 'realname': None, 'roles': None,
2202                       'creator': '1', 'age': 29.0, 'actor': '1',
2203                       'address': None}
2204             ,  '5' : {'username': 'grouplead2', 'assignable': None,
2205                       'supervisor': '3', 'realname': None, 'roles': None,
2206                       'creator': '1', 'age': 29.0, 'actor': '1',
2207                       'address': None}
2208             ,  '6' : {'username': 'worker1', 'assignable': None,
2209                       'supervisor': '4', 'realname': None, 'roles': None,
2210                       'creator': '1', 'age': 25.0, 'actor': '1',
2211                       'address': None}
2212             ,  '7' : {'username': 'worker2', 'assignable': None,
2213                       'supervisor': '4', 'realname': None, 'roles': None,
2214                       'creator': '1', 'age': 24.0, 'actor': '1',
2215                       'address': None}
2216             ,  '8' : {'username': 'worker3', 'assignable': None,
2217                       'supervisor': '5', 'realname': None, 'roles': None,
2218                       'creator': '1', 'age': 23.0, 'actor': '1',
2219                       'address': None}
2220             ,  '9' : {'username': 'worker4', 'assignable': None,
2221                       'supervisor': '5', 'realname': None, 'roles': None,
2222                       'creator': '1', 'age': 22.0, 'actor': '1',
2223                       'address': None}
2224             , '10' : {'username': 'worker5', 'assignable': None,
2225                       'supervisor': '5', 'realname': None, 'roles': None,
2226                       'creator': '1', 'age': 21.0, 'actor': '1',
2227                       'address': None}
2228             }
2229         foo = date.Interval('-1d')
2230         issue_result = \
2231             { '1' : {'title': 'ts1', 'status': '2', 'assignedto': '6',
2232                      'priority': '3', 'messages' : ['4'], 'nosy' : ['4']}
2233             , '2' : {'title': 'ts2', 'status': '1', 'assignedto': '6',
2234                      'priority': '3', 'messages' : ['4'], 'nosy' : ['5']}
2235             , '3' : {'title': 'ts4', 'status': '2', 'assignedto': '7',
2236                      'priority': '3', 'messages' : ['5']}
2237             , '4' : {'title': 'ts5', 'status': '1', 'assignedto': '8',
2238                      'priority': '3', 'messages' : ['6']}
2239             , '5' : {'title': 'ts6', 'status': '2', 'assignedto': '9',
2240                      'priority': '3', 'messages' : ['7']}
2241             , '6' : {'title': 'ts7', 'status': '1', 'assignedto': '10',
2242                      'priority': '3', 'messages' : ['8'], 'foo' : None}
2243             , '7' : {'title': 'ts8', 'status': '2', 'assignedto': '10',
2244                      'priority': '3', 'messages' : ['8'], 'foo' : foo}
2245             , '8' : {'title': 'ts9', 'status': '1', 'assignedto': '10',
2246                      'priority': '3', 'messages' : ['7', '8']}
2247             }
2248         result = []
2249         self.db.clearCache()
2250         for id in ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
2251             ('-','supervisor.supervisor'), ('-','supervisor'),
2252             ('+','username')]):
2253             result.append(id)
2254             nodeid = id
2255             for x in range(4):
2256                 assert(('user', nodeid) in self.db.cache)
2257                 n = self.db.user.getnode(nodeid)
2258                 for k, v in user_result[nodeid].iteritems():
2259                     ae((k, n[k]), (k, v))
2260                 for k in 'creation', 'activity':
2261                     assert(n[k])
2262                 nodeid = n.supervisor
2263             self.db.clearCache()
2264         ae (result, ['8', '9', '10', '6', '7', '1', '3', '2', '4', '5'])
2266         result = []
2267         self.db.clearCache()
2268         for id in filt(None, {},
2269             [('+','assignedto.supervisor.supervisor.supervisor'),
2270             ('+','assignedto.supervisor.supervisor'),
2271             ('-','assignedto.supervisor'), ('+','assignedto')]):
2272             result.append(id)
2273             assert(('issue', id) in self.db.cache)
2274             n = self.db.issue.getnode(id)
2275             for k, v in issue_result[id].iteritems():
2276                 ae((k, n[k]), (k, v))
2277             for k in 'creation', 'activity':
2278                 assert(n[k])
2279             nodeid = n.assignedto
2280             for x in range(4):
2281                 assert(('user', nodeid) in self.db.cache)
2282                 n = self.db.user.getnode(nodeid)
2283                 for k, v in user_result[nodeid].iteritems():
2284                     ae((k, n[k]), (k, v))
2285                 for k in 'creation', 'activity':
2286                     assert(n[k])
2287                 nodeid = n.supervisor
2288             self.db.clearCache()
2289         ae (result, ['4', '5', '6', '7', '8', '1', '2', '3'])
2292 class ClassicInitTest(unittest.TestCase):
2293     count = 0
2294     db = None
2296     def setUp(self):
2297         ClassicInitTest.count = ClassicInitTest.count + 1
2298         self.dirname = '_test_init_%s'%self.count
2299         try:
2300             shutil.rmtree(self.dirname)
2301         except OSError, error:
2302             if error.errno not in (errno.ENOENT, errno.ESRCH): raise
2304     def testCreation(self):
2305         ae = self.assertEqual
2307         # set up and open a tracker
2308         tracker = setupTracker(self.dirname, self.backend)
2309         # open the database
2310         db = self.db = tracker.open('test')
2312         # check the basics of the schema and initial data set
2313         l = db.priority.list()
2314         l.sort()
2315         ae(l, ['1', '2', '3', '4', '5'])
2316         l = db.status.list()
2317         l.sort()
2318         ae(l, ['1', '2', '3', '4', '5', '6', '7', '8'])
2319         l = db.keyword.list()
2320         ae(l, [])
2321         l = db.user.list()
2322         l.sort()
2323         ae(l, ['1', '2'])
2324         l = db.msg.list()
2325         ae(l, [])
2326         l = db.file.list()
2327         ae(l, [])
2328         l = db.issue.list()
2329         ae(l, [])
2331     def tearDown(self):
2332         if self.db is not None:
2333             self.db.close()
2334         try:
2335             shutil.rmtree(self.dirname)
2336         except OSError, error:
2337             if error.errno not in (errno.ENOENT, errno.ESRCH): raise
2339 class ConcurrentDBTest(ClassicInitTest):
2340     def testConcurrency(self):
2341         # The idea here is a read-modify-update cycle in the presence of
2342         # a cache that has to be properly handled. The same applies if
2343         # we extend a String or otherwise modify something that depends
2344         # on the previous value.
2346         # set up and open a tracker
2347         tracker = setupTracker(self.dirname, self.backend)
2348         # open the database
2349         self.db = tracker.open('admin')
2351         prio = '1'
2352         self.assertEqual(self.db.priority.get(prio, 'order'), 1.0)
2353         def inc(db):
2354             db.priority.set(prio, order=db.priority.get(prio, 'order') + 1)
2356         inc(self.db)
2358         db2 = tracker.open("admin")
2359         self.assertEqual(db2.priority.get(prio, 'order'), 1.0)
2360         db2.commit()
2361         self.db.commit()
2362         self.assertEqual(self.db.priority.get(prio, 'order'), 2.0)
2364         inc(db2)
2365         db2.commit()
2366         db2.clearCache()
2367         self.assertEqual(db2.priority.get(prio, 'order'), 3.0)
2368         db2.close()
2371 # vim: set et sts=4 sw=4 :