Code

- unify bool searching (filter method) across backends
[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, support
29 from mocknull import MockNull
31 config = configuration.CoreConfig()
32 config.DATABASE = "db"
33 config.RDBMS_NAME = "rounduptest"
34 config.RDBMS_HOST = "localhost"
35 config.RDBMS_USER = "rounduptest"
36 config.RDBMS_PASSWORD = "rounduptest"
37 #config.logging = MockNull()
38 # these TRACKER_WEB and MAIL_DOMAIN values are used in mailgw tests
39 config.MAIL_DOMAIN = "your.tracker.email.domain.example"
40 config.TRACKER_WEB = "http://tracker.example/cgi-bin/roundup.cgi/bugs/"
41 # uncomment the following to have excessive debug output from test cases
42 # FIXME: tracker logging level should be increased by -v arguments
43 #   to 'run_tests.py' script
44 #config.LOGGING_FILENAME = "/tmp/logfile"
45 #config.LOGGING_LEVEL = "DEBUG"
46 config.init_logging()
48 def setupTracker(dirname, backend="anydbm"):
49     """Install and initialize new tracker in dirname; return tracker instance.
51     If the directory exists, it is wiped out before the operation.
53     """
54     global config
55     try:
56         shutil.rmtree(dirname)
57     except OSError, error:
58         if error.errno not in (errno.ENOENT, errno.ESRCH): raise
59     # create the instance
60     init.install(dirname, os.path.join(os.path.dirname(__file__),
61                                        '..',
62                                        'share',
63                                        'roundup',
64                                        'templates',
65                                        'classic'))
66     init.write_select_db(dirname, backend)
67     config.save(os.path.join(dirname, 'config.ini'))
68     tracker = instance.open(dirname)
69     if tracker.exists():
70         tracker.nuke()
71         init.write_select_db(dirname, backend)
72     tracker.init(password.Password('sekrit'))
73     return tracker
75 def setupSchema(db, create, module):
76     status = module.Class(db, "status", name=String())
77     status.setkey("name")
78     priority = module.Class(db, "priority", name=String(), order=String())
79     priority.setkey("name")
80     user = module.Class(db, "user", username=String(), password=Password(),
81         assignable=Boolean(), age=Number(), roles=String(), address=String(),
82         supervisor=Link('user'),realname=String())
83     user.setkey("username")
84     file = module.FileClass(db, "file", name=String(), type=String(),
85         comment=String(indexme="yes"), fooz=Password())
86     file_nidx = module.FileClass(db, "file_nidx", content=String(indexme='no'))
87     issue = module.IssueClass(db, "issue", title=String(indexme="yes"),
88         status=Link("status"), nosy=Multilink("user"), deadline=Date(),
89         foo=Interval(), files=Multilink("file"), assignedto=Link('user'),
90         priority=Link('priority'), spam=Multilink('msg'),
91         feedback=Link('msg'))
92     stuff = module.Class(db, "stuff", stuff=String())
93     session = module.Class(db, 'session', title=String())
94     msg = module.FileClass(db, "msg", date=Date(),
95                            author=Link("user", do_journal='no'),
96                            files=Multilink('file'), inreplyto=String(),
97                            messageid=String(),
98                            recipients=Multilink("user", do_journal='no')
99                            )
100     session.disableJournalling()
101     db.post_init()
102     if create:
103         user.create(username="admin", roles='Admin',
104             password=password.Password('sekrit'))
105         user.create(username="fred", roles='User',
106             password=password.Password('sekrit'), address='fred@example.com')
107         status.create(name="unread")
108         status.create(name="in-progress")
109         status.create(name="testing")
110         status.create(name="resolved")
111         priority.create(name="feature", order="2")
112         priority.create(name="wish", order="3")
113         priority.create(name="bug", order="1")
114     db.commit()
116     # nosy tests require this
117     db.security.addPermissionToRole('User', 'View', 'msg')
119 class MyTestCase(unittest.TestCase):
120     def tearDown(self):
121         if hasattr(self, 'db'):
122             self.db.close()
123         if os.path.exists(config.DATABASE):
124             shutil.rmtree(config.DATABASE)
126 if os.environ.has_key('LOGGING_LEVEL'):
127     from roundup import rlog
128     config.logging = rlog.BasicLogging()
129     config.logging.setLevel(os.environ['LOGGING_LEVEL'])
130     config.logging.getLogger('hyperdb').setFormat('%(message)s')
132 class DBTest(MyTestCase):
133     def setUp(self):
134         # remove previous test, ignore errors
135         if os.path.exists(config.DATABASE):
136             shutil.rmtree(config.DATABASE)
137         os.makedirs(config.DATABASE + '/files')
138         self.open_database()
139         setupSchema(self.db, 1, self.module)
141     def open_database(self):
142         self.db = self.module.Database(config, 'admin')
144     def testRefresh(self):
145         self.db.refresh_database()
147     #
148     # automatic properties (well, the two easy ones anyway)
149     #
150     def testCreatorProperty(self):
151         i = self.db.issue
152         id1 = i.create(title='spam')
153         self.db.journaltag = 'fred'
154         id2 = i.create(title='spam')
155         self.assertNotEqual(id1, id2)
156         self.assertNotEqual(i.get(id1, 'creator'), i.get(id2, 'creator'))
158     def testActorProperty(self):
159         i = self.db.issue
160         id1 = i.create(title='spam')
161         self.db.journaltag = 'fred'
162         i.set(id1, title='asfasd')
163         self.assertNotEqual(i.get(id1, 'creator'), i.get(id1, 'actor'))
165     # ID number controls
166     def testIDGeneration(self):
167         id1 = self.db.issue.create(title="spam", status='1')
168         id2 = self.db.issue.create(title="eggs", status='2')
169         self.assertNotEqual(id1, id2)
170     def testIDSetting(self):
171         # XXX numeric ids
172         self.db.setid('issue', 10)
173         id2 = self.db.issue.create(title="eggs", status='2')
174         self.assertEqual('11', id2)
176     #
177     # basic operations
178     #
179     def testEmptySet(self):
180         id1 = self.db.issue.create(title="spam", status='1')
181         self.db.issue.set(id1)
183     # String
184     def testStringChange(self):
185         for commit in (0,1):
186             # test set & retrieve
187             nid = self.db.issue.create(title="spam", status='1')
188             self.assertEqual(self.db.issue.get(nid, 'title'), 'spam')
190             # change and make sure we retrieve the correct value
191             self.db.issue.set(nid, title='eggs')
192             if commit: self.db.commit()
193             self.assertEqual(self.db.issue.get(nid, 'title'), 'eggs')
195     def testStringUnset(self):
196         for commit in (0,1):
197             nid = self.db.issue.create(title="spam", status='1')
198             if commit: self.db.commit()
199             self.assertEqual(self.db.issue.get(nid, 'title'), 'spam')
200             # make sure we can unset
201             self.db.issue.set(nid, title=None)
202             if commit: self.db.commit()
203             self.assertEqual(self.db.issue.get(nid, "title"), None)
205     # FileClass "content" property (no unset test)
206     def testFileClassContentChange(self):
207         for commit in (0,1):
208             # test set & retrieve
209             nid = self.db.file.create(content="spam")
210             self.assertEqual(self.db.file.get(nid, 'content'), 'spam')
212             # change and make sure we retrieve the correct value
213             self.db.file.set(nid, content='eggs')
214             if commit: self.db.commit()
215             self.assertEqual(self.db.file.get(nid, 'content'), 'eggs')
217     def testStringUnicode(self):
218         # test set & retrieve
219         ustr = u'\xe4\xf6\xfc\u20ac'.encode('utf8')
220         nid = self.db.issue.create(title=ustr, status='1')
221         self.assertEqual(self.db.issue.get(nid, 'title'), ustr)
223         # change and make sure we retrieve the correct value
224         ustr2 = u'change \u20ac change'.encode('utf8')
225         self.db.issue.set(nid, title=ustr2)
226         self.db.commit()
227         self.assertEqual(self.db.issue.get(nid, 'title'), ustr2)
229     # Link
230     def testLinkChange(self):
231         self.assertRaises(IndexError, self.db.issue.create, title="spam",
232             status='100')
233         for commit in (0,1):
234             nid = self.db.issue.create(title="spam", status='1')
235             if commit: self.db.commit()
236             self.assertEqual(self.db.issue.get(nid, "status"), '1')
237             self.db.issue.set(nid, status='2')
238             if commit: self.db.commit()
239             self.assertEqual(self.db.issue.get(nid, "status"), '2')
241     def testLinkUnset(self):
242         for commit in (0,1):
243             nid = self.db.issue.create(title="spam", status='1')
244             if commit: self.db.commit()
245             self.db.issue.set(nid, status=None)
246             if commit: self.db.commit()
247             self.assertEqual(self.db.issue.get(nid, "status"), None)
249     # Multilink
250     def testMultilinkChange(self):
251         for commit in (0,1):
252             self.assertRaises(IndexError, self.db.issue.create, title="spam",
253                 nosy=['foo%s'%commit])
254             u1 = self.db.user.create(username='foo%s'%commit)
255             u2 = self.db.user.create(username='bar%s'%commit)
256             nid = self.db.issue.create(title="spam", nosy=[u1])
257             if commit: self.db.commit()
258             self.assertEqual(self.db.issue.get(nid, "nosy"), [u1])
259             self.db.issue.set(nid, nosy=[])
260             if commit: self.db.commit()
261             self.assertEqual(self.db.issue.get(nid, "nosy"), [])
262             self.db.issue.set(nid, nosy=[u1,u2])
263             if commit: self.db.commit()
264             l = [u1,u2]; l.sort()
265             m = self.db.issue.get(nid, "nosy"); m.sort()
266             self.assertEqual(l, m)
268             # verify that when we pass None to an Multilink it sets
269             # it to an empty list
270             self.db.issue.set(nid, nosy=None)
271             if commit: self.db.commit()
272             self.assertEqual(self.db.issue.get(nid, "nosy"), [])
274     def testMultilinkChangeIterable(self):
275         for commit in (0,1):
276             # invalid nosy value assertion
277             self.assertRaises(IndexError, self.db.issue.create, title='spam',
278                 nosy=['foo%s'%commit])
279             # invalid type for nosy create
280             self.assertRaises(TypeError, self.db.issue.create, title='spam',
281                 nosy=1)
282             u1 = self.db.user.create(username='foo%s'%commit)
283             u2 = self.db.user.create(username='bar%s'%commit)
284             # try a couple of the built-in iterable types to make
285             # sure that we accept them and handle them properly
286             # try a set as input for the multilink
287             nid = self.db.issue.create(title="spam", nosy=set(u1))
288             if commit: self.db.commit()
289             self.assertEqual(self.db.issue.get(nid, "nosy"), [u1])
290             self.assertRaises(TypeError, self.db.issue.set, nid,
291                 nosy='invalid type')
292             # test with a tuple
293             self.db.issue.set(nid, nosy=tuple())
294             if commit: self.db.commit()
295             self.assertEqual(self.db.issue.get(nid, "nosy"), [])
296             # make sure we accept a frozen set
297             self.db.issue.set(nid, nosy=set([u1,u2]))
298             if commit: self.db.commit()
299             l = [u1,u2]; l.sort()
300             m = self.db.issue.get(nid, "nosy"); m.sort()
301             self.assertEqual(l, m)
304 # XXX one day, maybe...
305 #    def testMultilinkOrdering(self):
306 #        for i in range(10):
307 #            self.db.user.create(username='foo%s'%i)
308 #        i = self.db.issue.create(title="spam", nosy=['5','3','12','4'])
309 #        self.db.commit()
310 #        l = self.db.issue.get(i, "nosy")
311 #        # all backends should return the Multilink numeric-id-sorted
312 #        self.assertEqual(l, ['3', '4', '5', '12'])
314     # Date
315     def testDateChange(self):
316         self.assertRaises(TypeError, self.db.issue.create,
317             title='spam', deadline=1)
318         for commit in (0,1):
319             nid = self.db.issue.create(title="spam", status='1')
320             self.assertRaises(TypeError, self.db.issue.set, nid, deadline=1)
321             a = self.db.issue.get(nid, "deadline")
322             if commit: self.db.commit()
323             self.db.issue.set(nid, deadline=date.Date())
324             b = self.db.issue.get(nid, "deadline")
325             if commit: self.db.commit()
326             self.assertNotEqual(a, b)
327             self.assertNotEqual(b, date.Date('1970-1-1.00:00:00'))
328             # The 1970 date will fail for metakit -- it is used
329             # internally for storing NULL. The others would, too
330             # because metakit tries to convert date.timestamp to an int
331             # for storing and fails with an overflow.
332             for d in [date.Date (x) for x in '2038', '1970', '0033', '9999']:
333                 self.db.issue.set(nid, deadline=d)
334                 if commit: self.db.commit()
335                 c = self.db.issue.get(nid, "deadline")
336                 self.assertEqual(c, d)
338     def testDateLeapYear(self):
339         nid = self.db.issue.create(title='spam', status='1',
340             deadline=date.Date('2008-02-29'))
341         self.assertEquals(str(self.db.issue.get(nid, 'deadline')),
342             '2008-02-29.00:00:00')
343         self.assertEquals(self.db.issue.filter(None,
344             {'deadline': '2008-02-29'}), [nid])
345         self.db.issue.set(nid, deadline=date.Date('2008-03-01'))
346         self.assertEquals(str(self.db.issue.get(nid, 'deadline')),
347             '2008-03-01.00:00:00')
348         self.assertEquals(self.db.issue.filter(None,
349             {'deadline': '2008-02-29'}), [])
351     def testDateUnset(self):
352         for commit in (0,1):
353             nid = self.db.issue.create(title="spam", status='1')
354             self.db.issue.set(nid, deadline=date.Date())
355             if commit: self.db.commit()
356             self.assertNotEqual(self.db.issue.get(nid, "deadline"), None)
357             self.db.issue.set(nid, deadline=None)
358             if commit: self.db.commit()
359             self.assertEqual(self.db.issue.get(nid, "deadline"), None)
361     # Interval
362     def testIntervalChange(self):
363         self.assertRaises(TypeError, self.db.issue.create,
364             title='spam', foo=1)
365         for commit in (0,1):
366             nid = self.db.issue.create(title="spam", status='1')
367             self.assertRaises(TypeError, self.db.issue.set, nid, foo=1)
368             if commit: self.db.commit()
369             a = self.db.issue.get(nid, "foo")
370             i = date.Interval('-1d')
371             self.db.issue.set(nid, foo=i)
372             if commit: self.db.commit()
373             self.assertNotEqual(self.db.issue.get(nid, "foo"), a)
374             self.assertEqual(i, self.db.issue.get(nid, "foo"))
375             j = date.Interval('1y')
376             self.db.issue.set(nid, foo=j)
377             if commit: self.db.commit()
378             self.assertNotEqual(self.db.issue.get(nid, "foo"), i)
379             self.assertEqual(j, self.db.issue.get(nid, "foo"))
381     def testIntervalUnset(self):
382         for commit in (0,1):
383             nid = self.db.issue.create(title="spam", status='1')
384             self.db.issue.set(nid, foo=date.Interval('-1d'))
385             if commit: self.db.commit()
386             self.assertNotEqual(self.db.issue.get(nid, "foo"), None)
387             self.db.issue.set(nid, foo=None)
388             if commit: self.db.commit()
389             self.assertEqual(self.db.issue.get(nid, "foo"), None)
391     # Boolean
392     def testBooleanSet(self):
393         nid = self.db.user.create(username='one', assignable=1)
394         self.assertEqual(self.db.user.get(nid, "assignable"), 1)
395         nid = self.db.user.create(username='two', assignable=0)
396         self.assertEqual(self.db.user.get(nid, "assignable"), 0)
398     def testBooleanChange(self):
399         userid = self.db.user.create(username='foo', assignable=1)
400         self.assertEqual(1, self.db.user.get(userid, 'assignable'))
401         self.db.user.set(userid, assignable=0)
402         self.assertEqual(self.db.user.get(userid, 'assignable'), 0)
403         self.db.user.set(userid, assignable=1)
404         self.assertEqual(self.db.user.get(userid, 'assignable'), 1)
406     def testBooleanUnset(self):
407         nid = self.db.user.create(username='foo', assignable=1)
408         self.db.user.set(nid, assignable=None)
409         self.assertEqual(self.db.user.get(nid, "assignable"), None)
411     # Number
412     def testNumberChange(self):
413         nid = self.db.user.create(username='foo', age=1)
414         self.assertEqual(1, self.db.user.get(nid, 'age'))
415         self.db.user.set(nid, age=3)
416         self.assertNotEqual(self.db.user.get(nid, 'age'), 1)
417         self.db.user.set(nid, age=1.0)
418         self.assertEqual(self.db.user.get(nid, 'age'), 1)
419         self.db.user.set(nid, age=0)
420         self.assertEqual(self.db.user.get(nid, 'age'), 0)
422         nid = self.db.user.create(username='bar', age=0)
423         self.assertEqual(self.db.user.get(nid, 'age'), 0)
425     def testNumberUnset(self):
426         nid = self.db.user.create(username='foo', age=1)
427         self.db.user.set(nid, age=None)
428         self.assertEqual(self.db.user.get(nid, "age"), None)
430     # Password
431     def testPasswordChange(self):
432         x = password.Password('x')
433         userid = self.db.user.create(username='foo', password=x)
434         self.assertEqual(x, self.db.user.get(userid, 'password'))
435         self.assertEqual(self.db.user.get(userid, 'password'), 'x')
436         y = password.Password('y')
437         self.db.user.set(userid, password=y)
438         self.assertEqual(self.db.user.get(userid, 'password'), 'y')
439         self.assertRaises(TypeError, self.db.user.create, userid,
440             username='bar', password='x')
441         self.assertRaises(TypeError, self.db.user.set, userid, password='x')
443     def testPasswordUnset(self):
444         x = password.Password('x')
445         nid = self.db.user.create(username='foo', password=x)
446         self.db.user.set(nid, assignable=None)
447         self.assertEqual(self.db.user.get(nid, "assignable"), None)
449     # key value
450     def testKeyValue(self):
451         self.assertRaises(ValueError, self.db.user.create)
453         newid = self.db.user.create(username="spam")
454         self.assertEqual(self.db.user.lookup('spam'), newid)
455         self.db.commit()
456         self.assertEqual(self.db.user.lookup('spam'), newid)
457         self.db.user.retire(newid)
458         self.assertRaises(KeyError, self.db.user.lookup, 'spam')
460         # use the key again now that the old is retired
461         newid2 = self.db.user.create(username="spam")
462         self.assertNotEqual(newid, newid2)
463         # try to restore old node. this shouldn't succeed!
464         self.assertRaises(KeyError, self.db.user.restore, newid)
466         self.assertRaises(TypeError, self.db.issue.lookup, 'fubar')
468     # label property
469     def testLabelProp(self):
470         # key prop
471         self.assertEqual(self.db.status.labelprop(), 'name')
472         self.assertEqual(self.db.user.labelprop(), 'username')
473         # title
474         self.assertEqual(self.db.issue.labelprop(), 'title')
475         # name
476         self.assertEqual(self.db.file.labelprop(), 'name')
477         # id
478         self.assertEqual(self.db.stuff.labelprop(default_to_id=1), 'id')
480     # retirement
481     def testRetire(self):
482         self.db.issue.create(title="spam", status='1')
483         b = self.db.status.get('1', 'name')
484         a = self.db.status.list()
485         nodeids = self.db.status.getnodeids()
486         self.db.status.retire('1')
487         others = nodeids[:]
488         others.remove('1')
490         self.assertEqual(set(self.db.status.getnodeids()),
491             set(nodeids))
492         self.assertEqual(set(self.db.status.getnodeids(retired=True)),
493             set(['1']))
494         self.assertEqual(set(self.db.status.getnodeids(retired=False)),
495             set(others))
497         self.assert_(self.db.status.is_retired('1'))
499         # make sure the list is different
500         self.assertNotEqual(a, self.db.status.list())
502         # can still access the node if necessary
503         self.assertEqual(self.db.status.get('1', 'name'), b)
504         self.assertRaises(IndexError, self.db.status.set, '1', name='hello')
505         self.db.commit()
506         self.assert_(self.db.status.is_retired('1'))
507         self.assertEqual(self.db.status.get('1', 'name'), b)
508         self.assertNotEqual(a, self.db.status.list())
510         # try to restore retired node
511         self.db.status.restore('1')
513         self.assert_(not self.db.status.is_retired('1'))
515     def testCacheCreateSet(self):
516         self.db.issue.create(title="spam", status='1')
517         a = self.db.issue.get('1', 'title')
518         self.assertEqual(a, 'spam')
519         self.db.issue.set('1', title='ham')
520         b = self.db.issue.get('1', 'title')
521         self.assertEqual(b, 'ham')
523     def testSerialisation(self):
524         nid = self.db.issue.create(title="spam", status='1',
525             deadline=date.Date(), foo=date.Interval('-1d'))
526         self.db.commit()
527         assert isinstance(self.db.issue.get(nid, 'deadline'), date.Date)
528         assert isinstance(self.db.issue.get(nid, 'foo'), date.Interval)
529         uid = self.db.user.create(username="fozzy",
530             password=password.Password('t. bear'))
531         self.db.commit()
532         assert isinstance(self.db.user.get(uid, 'password'), password.Password)
534     def testTransactions(self):
535         # remember the number of items we started
536         num_issues = len(self.db.issue.list())
537         num_files = self.db.numfiles()
538         self.db.issue.create(title="don't commit me!", status='1')
539         self.assertNotEqual(num_issues, len(self.db.issue.list()))
540         self.db.rollback()
541         self.assertEqual(num_issues, len(self.db.issue.list()))
542         self.db.issue.create(title="please commit me!", status='1')
543         self.assertNotEqual(num_issues, len(self.db.issue.list()))
544         self.db.commit()
545         self.assertNotEqual(num_issues, len(self.db.issue.list()))
546         self.db.rollback()
547         self.assertNotEqual(num_issues, len(self.db.issue.list()))
548         self.db.file.create(name="test", type="text/plain", content="hi")
549         self.db.rollback()
550         self.assertEqual(num_files, self.db.numfiles())
551         for i in range(10):
552             self.db.file.create(name="test", type="text/plain",
553                     content="hi %d"%(i))
554             self.db.commit()
555         num_files2 = self.db.numfiles()
556         self.assertNotEqual(num_files, num_files2)
557         self.db.file.create(name="test", type="text/plain", content="hi")
558         self.db.rollback()
559         self.assertNotEqual(num_files, self.db.numfiles())
560         self.assertEqual(num_files2, self.db.numfiles())
562         # rollback / cache interaction
563         name1 = self.db.user.get('1', 'username')
564         self.db.user.set('1', username = name1+name1)
565         # get the prop so the info's forced into the cache (if there is one)
566         self.db.user.get('1', 'username')
567         self.db.rollback()
568         name2 = self.db.user.get('1', 'username')
569         self.assertEqual(name1, name2)
571     def testDestroyBlob(self):
572         # destroy an uncommitted blob
573         f1 = self.db.file.create(content='hello', type="text/plain")
574         self.db.commit()
575         fn = self.db.filename('file', f1)
576         self.db.file.destroy(f1)
577         self.db.commit()
578         self.assertEqual(os.path.exists(fn), False)
580     def testDestroyNoJournalling(self):
581         self.innerTestDestroy(klass=self.db.session)
583     def testDestroyJournalling(self):
584         self.innerTestDestroy(klass=self.db.issue)
586     def innerTestDestroy(self, klass):
587         newid = klass.create(title='Mr Friendly')
588         n = len(klass.list())
589         self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
590         count = klass.count()
591         klass.destroy(newid)
592         self.assertNotEqual(count, klass.count())
593         self.assertRaises(IndexError, klass.get, newid, 'title')
594         self.assertNotEqual(len(klass.list()), n)
595         if klass.do_journal:
596             self.assertRaises(IndexError, klass.history, newid)
598         # now with a commit
599         newid = klass.create(title='Mr Friendly')
600         n = len(klass.list())
601         self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
602         self.db.commit()
603         count = klass.count()
604         klass.destroy(newid)
605         self.assertNotEqual(count, klass.count())
606         self.assertRaises(IndexError, klass.get, newid, 'title')
607         self.db.commit()
608         self.assertRaises(IndexError, klass.get, newid, 'title')
609         self.assertNotEqual(len(klass.list()), n)
610         if klass.do_journal:
611             self.assertRaises(IndexError, klass.history, newid)
613         # now with a rollback
614         newid = klass.create(title='Mr Friendly')
615         n = len(klass.list())
616         self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
617         self.db.commit()
618         count = klass.count()
619         klass.destroy(newid)
620         self.assertNotEqual(len(klass.list()), n)
621         self.assertRaises(IndexError, klass.get, newid, 'title')
622         self.db.rollback()
623         self.assertEqual(count, klass.count())
624         self.assertEqual(klass.get(newid, 'title'), 'Mr Friendly')
625         self.assertEqual(len(klass.list()), n)
626         if klass.do_journal:
627             self.assertNotEqual(klass.history(newid), [])
629     def testExceptions(self):
630         # this tests the exceptions that should be raised
631         ar = self.assertRaises
633         ar(KeyError, self.db.getclass, 'fubar')
635         #
636         # class create
637         #
638         # string property
639         ar(TypeError, self.db.status.create, name=1)
640         # id, creation, creator and activity properties are reserved
641         ar(KeyError, self.db.status.create, id=1)
642         ar(KeyError, self.db.status.create, creation=1)
643         ar(KeyError, self.db.status.create, creator=1)
644         ar(KeyError, self.db.status.create, activity=1)
645         ar(KeyError, self.db.status.create, actor=1)
646         # invalid property name
647         ar(KeyError, self.db.status.create, foo='foo')
648         # key name clash
649         ar(ValueError, self.db.status.create, name='unread')
650         # invalid link index
651         ar(IndexError, self.db.issue.create, title='foo', status='bar')
652         # invalid link value
653         ar(ValueError, self.db.issue.create, title='foo', status=1)
654         # invalid multilink type
655         ar(TypeError, self.db.issue.create, title='foo', status='1',
656             nosy='hello')
657         # invalid multilink index type
658         ar(ValueError, self.db.issue.create, title='foo', status='1',
659             nosy=[1])
660         # invalid multilink index
661         ar(IndexError, self.db.issue.create, title='foo', status='1',
662             nosy=['10'])
664         #
665         # key property
666         #
667         # key must be a String
668         ar(TypeError, self.db.file.setkey, 'fooz')
669         # key must exist
670         ar(KeyError, self.db.file.setkey, 'fubar')
672         #
673         # class get
674         #
675         # invalid node id
676         ar(IndexError, self.db.issue.get, '99', 'title')
677         # invalid property name
678         ar(KeyError, self.db.status.get, '2', 'foo')
680         #
681         # class set
682         #
683         # invalid node id
684         ar(IndexError, self.db.issue.set, '99', title='foo')
685         # invalid property name
686         ar(KeyError, self.db.status.set, '1', foo='foo')
687         # string property
688         ar(TypeError, self.db.status.set, '1', name=1)
689         # key name clash
690         ar(ValueError, self.db.status.set, '2', name='unread')
691         # set up a valid issue for me to work on
692         id = self.db.issue.create(title="spam", status='1')
693         # invalid link index
694         ar(IndexError, self.db.issue.set, id, title='foo', status='bar')
695         # invalid link value
696         ar(ValueError, self.db.issue.set, id, title='foo', status=1)
697         # invalid multilink type
698         ar(TypeError, self.db.issue.set, id, title='foo', status='1',
699             nosy='hello')
700         # invalid multilink index type
701         ar(ValueError, self.db.issue.set, id, title='foo', status='1',
702             nosy=[1])
703         # invalid multilink index
704         ar(IndexError, self.db.issue.set, id, title='foo', status='1',
705             nosy=['10'])
706         # NOTE: the following increment the username to avoid problems
707         # within metakit's backend (it creates the node, and then sets the
708         # info, so the create (and by a fluke the username set) go through
709         # before the age/assignable/etc. set, which raises the exception)
710         # invalid number value
711         ar(TypeError, self.db.user.create, username='foo', age='a')
712         # invalid boolean value
713         ar(TypeError, self.db.user.create, username='foo2', assignable='true')
714         nid = self.db.user.create(username='foo3')
715         # invalid number value
716         ar(TypeError, self.db.user.set, nid, age='a')
717         # invalid boolean value
718         ar(TypeError, self.db.user.set, nid, assignable='true')
720     def testAuditors(self):
721         class test:
722             called = False
723             def call(self, *args): self.called = True
724         create = test()
726         self.db.user.audit('create', create.call)
727         self.db.user.create(username="mary")
728         self.assertEqual(create.called, True)
730         set = test()
731         self.db.user.audit('set', set.call)
732         self.db.user.set('1', username="joe")
733         self.assertEqual(set.called, True)
735         retire = test()
736         self.db.user.audit('retire', retire.call)
737         self.db.user.retire('1')
738         self.assertEqual(retire.called, True)
740     def testAuditorTwo(self):
741         class test:
742             n = 0
743             def a(self, *args): self.call_a = self.n; self.n += 1
744             def b(self, *args): self.call_b = self.n; self.n += 1
745             def c(self, *args): self.call_c = self.n; self.n += 1
746         test = test()
747         self.db.user.audit('create', test.b, 1)
748         self.db.user.audit('create', test.a, 1)
749         self.db.user.audit('create', test.c, 2)
750         self.db.user.create(username="mary")
751         self.assertEqual(test.call_a, 0)
752         self.assertEqual(test.call_b, 1)
753         self.assertEqual(test.call_c, 2)
755     def testJournals(self):
756         muid = self.db.user.create(username="mary")
757         self.db.user.create(username="pete")
758         self.db.issue.create(title="spam", status='1')
759         self.db.commit()
761         # journal entry for issue create
762         journal = self.db.getjournal('issue', '1')
763         self.assertEqual(1, len(journal))
764         (nodeid, date_stamp, journaltag, action, params) = journal[0]
765         self.assertEqual(nodeid, '1')
766         self.assertEqual(journaltag, self.db.user.lookup('admin'))
767         self.assertEqual(action, 'create')
768         keys = params.keys()
769         keys.sort()
770         self.assertEqual(keys, [])
772         # journal entry for link
773         journal = self.db.getjournal('user', '1')
774         self.assertEqual(1, len(journal))
775         self.db.issue.set('1', assignedto='1')
776         self.db.commit()
777         journal = self.db.getjournal('user', '1')
778         self.assertEqual(2, len(journal))
779         (nodeid, date_stamp, journaltag, action, params) = journal[1]
780         self.assertEqual('1', nodeid)
781         self.assertEqual('1', journaltag)
782         self.assertEqual('link', action)
783         self.assertEqual(('issue', '1', 'assignedto'), params)
785         # wait a bit to keep proper order of journal entries
786         time.sleep(0.01)
787         # journal entry for unlink
788         self.db.setCurrentUser('mary')
789         self.db.issue.set('1', assignedto='2')
790         self.db.commit()
791         journal = self.db.getjournal('user', '1')
792         self.assertEqual(3, len(journal))
793         (nodeid, date_stamp, journaltag, action, params) = journal[2]
794         self.assertEqual('1', nodeid)
795         self.assertEqual(muid, journaltag)
796         self.assertEqual('unlink', action)
797         self.assertEqual(('issue', '1', 'assignedto'), params)
799         # test disabling journalling
800         # ... get the last entry
801         jlen = len(self.db.getjournal('user', '1'))
802         self.db.issue.disableJournalling()
803         self.db.issue.set('1', title='hello world')
804         self.db.commit()
805         # see if the change was journalled when it shouldn't have been
806         self.assertEqual(jlen,  len(self.db.getjournal('user', '1')))
807         jlen = len(self.db.getjournal('issue', '1'))
808         self.db.issue.enableJournalling()
809         self.db.issue.set('1', title='hello world 2')
810         self.db.commit()
811         # see if the change was journalled
812         self.assertNotEqual(jlen,  len(self.db.getjournal('issue', '1')))
814     def testJournalPreCommit(self):
815         id = self.db.user.create(username="mary")
816         self.assertEqual(len(self.db.getjournal('user', id)), 1)
817         self.db.commit()
819     def testPack(self):
820         id = self.db.issue.create(title="spam", status='1')
821         self.db.commit()
822         time.sleep(1)
823         self.db.issue.set(id, status='2')
824         self.db.commit()
826         # sleep for at least a second, then get a date to pack at
827         time.sleep(1)
828         pack_before = date.Date('.')
830         # wait another second and add one more entry
831         time.sleep(1)
832         self.db.issue.set(id, status='3')
833         self.db.commit()
834         jlen = len(self.db.getjournal('issue', id))
836         # pack
837         self.db.pack(pack_before)
839         # we should have the create and last set entries now
840         self.assertEqual(jlen-1, len(self.db.getjournal('issue', id)))
842     def testIndexerSearching(self):
843         f1 = self.db.file.create(content='hello', type="text/plain")
844         # content='world' has the wrong content-type and won't be indexed
845         f2 = self.db.file.create(content='world', type="text/frozz",
846             comment='blah blah')
847         i1 = self.db.issue.create(files=[f1, f2], title="flebble plop")
848         i2 = self.db.issue.create(title="flebble the frooz")
849         self.db.commit()
850         self.assertEquals(self.db.indexer.search([], self.db.issue), {})
851         self.assertEquals(self.db.indexer.search(['hello'], self.db.issue),
852             {i1: {'files': [f1]}})
853         # content='world' has the wrong content-type and shouldn't be indexed
854         self.assertEquals(self.db.indexer.search(['world'], self.db.issue), {})
855         self.assertEquals(self.db.indexer.search(['frooz'], self.db.issue),
856             {i2: {}})
857         self.assertEquals(self.db.indexer.search(['flebble'], self.db.issue),
858             {i1: {}, i2: {}})
860         # test AND'ing of search terms
861         self.assertEquals(self.db.indexer.search(['frooz', 'flebble'],
862             self.db.issue), {i2: {}})
864         # unindexed stopword
865         self.assertEquals(self.db.indexer.search(['the'], self.db.issue), {})
867     def testIndexerSearchingLink(self):
868         m1 = self.db.msg.create(content="one two")
869         i1 = self.db.issue.create(messages=[m1])
870         m2 = self.db.msg.create(content="two three")
871         i2 = self.db.issue.create(feedback=m2)
872         self.db.commit()
873         self.assertEquals(self.db.indexer.search(['two'], self.db.issue),
874             {i1: {'messages': [m1]}, i2: {'feedback': [m2]}})
876     def testIndexerSearchMulti(self):
877         m1 = self.db.msg.create(content="one two")
878         m2 = self.db.msg.create(content="two three")
879         i1 = self.db.issue.create(messages=[m1])
880         i2 = self.db.issue.create(spam=[m2])
881         self.db.commit()
882         self.assertEquals(self.db.indexer.search([], self.db.issue), {})
883         self.assertEquals(self.db.indexer.search(['one'], self.db.issue),
884             {i1: {'messages': [m1]}})
885         self.assertEquals(self.db.indexer.search(['two'], self.db.issue),
886             {i1: {'messages': [m1]}, i2: {'spam': [m2]}})
887         self.assertEquals(self.db.indexer.search(['three'], self.db.issue),
888             {i2: {'spam': [m2]}})
890     def testReindexingChange(self):
891         search = self.db.indexer.search
892         issue = self.db.issue
893         i1 = issue.create(title="flebble plop")
894         i2 = issue.create(title="flebble frooz")
895         self.db.commit()
896         self.assertEquals(search(['plop'], issue), {i1: {}})
897         self.assertEquals(search(['flebble'], issue), {i1: {}, i2: {}})
899         # change i1's title
900         issue.set(i1, title="plop")
901         self.db.commit()
902         self.assertEquals(search(['plop'], issue), {i1: {}})
903         self.assertEquals(search(['flebble'], issue), {i2: {}})
905     def testReindexingClear(self):
906         search = self.db.indexer.search
907         issue = self.db.issue
908         i1 = issue.create(title="flebble plop")
909         i2 = issue.create(title="flebble frooz")
910         self.db.commit()
911         self.assertEquals(search(['plop'], issue), {i1: {}})
912         self.assertEquals(search(['flebble'], issue), {i1: {}, i2: {}})
914         # unset i1's title
915         issue.set(i1, title="")
916         self.db.commit()
917         self.assertEquals(search(['plop'], issue), {})
918         self.assertEquals(search(['flebble'], issue), {i2: {}})
920     def testFileClassReindexing(self):
921         f1 = self.db.file.create(content='hello')
922         f2 = self.db.file.create(content='hello, world')
923         i1 = self.db.issue.create(files=[f1, f2])
924         self.db.commit()
925         d = self.db.indexer.search(['hello'], self.db.issue)
926         self.assert_(d.has_key(i1))
927         d[i1]['files'].sort()
928         self.assertEquals(d, {i1: {'files': [f1, f2]}})
929         self.assertEquals(self.db.indexer.search(['world'], self.db.issue),
930             {i1: {'files': [f2]}})
931         self.db.file.set(f1, content="world")
932         self.db.commit()
933         d = self.db.indexer.search(['world'], self.db.issue)
934         d[i1]['files'].sort()
935         self.assertEquals(d, {i1: {'files': [f1, f2]}})
936         self.assertEquals(self.db.indexer.search(['hello'], self.db.issue),
937             {i1: {'files': [f2]}})
939     def testFileClassIndexingNoNoNo(self):
940         f1 = self.db.file.create(content='hello')
941         self.db.commit()
942         self.assertEquals(self.db.indexer.search(['hello'], self.db.file),
943             {'1': {}})
945         f1 = self.db.file_nidx.create(content='hello')
946         self.db.commit()
947         self.assertEquals(self.db.indexer.search(['hello'], self.db.file_nidx),
948             {})
950     def testForcedReindexing(self):
951         self.db.issue.create(title="flebble frooz")
952         self.db.commit()
953         self.assertEquals(self.db.indexer.search(['flebble'], self.db.issue),
954             {'1': {}})
955         self.db.indexer.quiet = 1
956         self.db.indexer.force_reindex()
957         self.db.post_init()
958         self.db.indexer.quiet = 9
959         self.assertEquals(self.db.indexer.search(['flebble'], self.db.issue),
960             {'1': {}})
962     def testIndexingPropertiesOnImport(self):
963         # import an issue
964         title = 'Bzzt'
965         nodeid = self.db.issue.import_list(['title', 'messages', 'files',
966             'spam', 'nosy', 'superseder'], [repr(title), '[]', '[]',
967             '[]', '[]', '[]'])
968         self.db.commit()
970         # Content of title attribute is indexed
971         self.assertEquals(self.db.indexer.search([title], self.db.issue),
972             {str(nodeid):{}})
975     #
976     # searching tests follow
977     #
978     def testFindIncorrectProperty(self):
979         self.assertRaises(TypeError, self.db.issue.find, title='fubar')
981     def _find_test_setup(self):
982         self.db.file.create(content='')
983         self.db.file.create(content='')
984         self.db.user.create(username='')
985         one = self.db.issue.create(status="1", nosy=['1'])
986         two = self.db.issue.create(status="2", nosy=['2'], files=['1'],
987             assignedto='2')
988         three = self.db.issue.create(status="1", nosy=['1','2'])
989         four = self.db.issue.create(status="3", assignedto='1',
990             files=['1','2'])
991         return one, two, three, four
993     def testFindLink(self):
994         one, two, three, four = self._find_test_setup()
995         got = self.db.issue.find(status='1')
996         got.sort()
997         self.assertEqual(got, [one, three])
998         got = self.db.issue.find(status={'1':1})
999         got.sort()
1000         self.assertEqual(got, [one, three])
1002     def testFindLinkFail(self):
1003         self._find_test_setup()
1004         self.assertEqual(self.db.issue.find(status='4'), [])
1005         self.assertEqual(self.db.issue.find(status={'4':1}), [])
1007     def testFindLinkUnset(self):
1008         one, two, three, four = self._find_test_setup()
1009         got = self.db.issue.find(assignedto=None)
1010         got.sort()
1011         self.assertEqual(got, [one, three])
1012         got = self.db.issue.find(assignedto={None:1})
1013         got.sort()
1014         self.assertEqual(got, [one, three])
1016     def testFindMultipleLink(self):
1017         one, two, three, four = self._find_test_setup()
1018         l = self.db.issue.find(status={'1':1, '3':1})
1019         l.sort()
1020         self.assertEqual(l, [one, three, four])
1021         l = self.db.issue.find(assignedto={None:1, '1':1})
1022         l.sort()
1023         self.assertEqual(l, [one, three, four])
1025     def testFindMultilink(self):
1026         one, two, three, four = self._find_test_setup()
1027         got = self.db.issue.find(nosy='2')
1028         got.sort()
1029         self.assertEqual(got, [two, three])
1030         got = self.db.issue.find(nosy={'2':1})
1031         got.sort()
1032         self.assertEqual(got, [two, three])
1033         got = self.db.issue.find(nosy={'2':1}, files={})
1034         got.sort()
1035         self.assertEqual(got, [two, three])
1037     def testFindMultiMultilink(self):
1038         one, two, three, four = self._find_test_setup()
1039         got = self.db.issue.find(nosy='2', files='1')
1040         got.sort()
1041         self.assertEqual(got, [two, three, four])
1042         got = self.db.issue.find(nosy={'2':1}, files={'1':1})
1043         got.sort()
1044         self.assertEqual(got, [two, three, four])
1046     def testFindMultilinkFail(self):
1047         self._find_test_setup()
1048         self.assertEqual(self.db.issue.find(nosy='3'), [])
1049         self.assertEqual(self.db.issue.find(nosy={'3':1}), [])
1051     def testFindMultilinkUnset(self):
1052         self._find_test_setup()
1053         self.assertEqual(self.db.issue.find(nosy={}), [])
1055     def testFindLinkAndMultilink(self):
1056         one, two, three, four = self._find_test_setup()
1057         got = self.db.issue.find(status='1', nosy='2')
1058         got.sort()
1059         self.assertEqual(got, [one, two, three])
1060         got = self.db.issue.find(status={'1':1}, nosy={'2':1})
1061         got.sort()
1062         self.assertEqual(got, [one, two, three])
1064     def testFindRetired(self):
1065         one, two, three, four = self._find_test_setup()
1066         self.assertEqual(len(self.db.issue.find(status='1')), 2)
1067         self.db.issue.retire(one)
1068         self.assertEqual(len(self.db.issue.find(status='1')), 1)
1070     def testStringFind(self):
1071         self.assertRaises(TypeError, self.db.issue.stringFind, status='1')
1073         ids = []
1074         ids.append(self.db.issue.create(title="spam"))
1075         self.db.issue.create(title="not spam")
1076         ids.append(self.db.issue.create(title="spam"))
1077         ids.sort()
1078         got = self.db.issue.stringFind(title='spam')
1079         got.sort()
1080         self.assertEqual(got, ids)
1081         self.assertEqual(self.db.issue.stringFind(title='fubar'), [])
1083         # test retiring a node
1084         self.db.issue.retire(ids[0])
1085         self.assertEqual(len(self.db.issue.stringFind(title='spam')), 1)
1087     def filteringSetup(self):
1088         for user in (
1089                 {'username': 'bleep', 'age': 1, 'assignable': True},
1090                 {'username': 'blop', 'age': 1.5, 'assignable': True},
1091                 {'username': 'blorp', 'age': 2, 'assignable': False}):
1092             self.db.user.create(**user)
1093         iss = self.db.issue
1094         file_content = ''.join([chr(i) for i in range(255)])
1095         f = self.db.file.create(content=file_content)
1096         for issue in (
1097                 {'title': 'issue one', 'status': '2', 'assignedto': '1',
1098                     'foo': date.Interval('1:10'), 'priority': '3',
1099                     'deadline': date.Date('2003-02-16.22:50')},
1100                 {'title': 'issue two', 'status': '1', 'assignedto': '2',
1101                     'foo': date.Interval('1d'), 'priority': '3',
1102                     'deadline': date.Date('2003-01-01.00:00')},
1103                 {'title': 'issue three', 'status': '1', 'priority': '2',
1104                     'nosy': ['1','2'], 'deadline': date.Date('2003-02-18')},
1105                 {'title': 'non four', 'status': '3',
1106                     'foo': date.Interval('0:10'), 'priority': '2',
1107                     'nosy': ['1','2','3'], 'deadline': date.Date('2004-03-08'),
1108                     'files': [f]}):
1109             self.db.issue.create(**issue)
1110         self.db.commit()
1111         return self.assertEqual, self.db.issue.filter
1113     def testFilteringID(self):
1114         ae, filt = self.filteringSetup()
1115         ae(filt(None, {'id': '1'}, ('+','id'), (None,None)), ['1'])
1116         ae(filt(None, {'id': '2'}, ('+','id'), (None,None)), ['2'])
1117         ae(filt(None, {'id': '100'}, ('+','id'), (None,None)), [])
1119     def testFilteringBoolean(self):
1120         self.filteringSetup()
1121         ae, filt = self.assertEqual, self.db.user.filter
1122         a = 'assignable'
1123         ae(filt(None, {a: '1'}, ('+','id'), (None,None)), ['3','4'])
1124         ae(filt(None, {a: '0'}, ('+','id'), (None,None)), ['5'])
1125         ae(filt(None, {a: ['1']}, ('+','id'), (None,None)), ['3','4'])
1126         ae(filt(None, {a: ['0']}, ('+','id'), (None,None)), ['5'])
1127         ae(filt(None, {a: ['0','1']}, ('+','id'), (None,None)), ['3','4','5'])
1128         ae(filt(None, {a: 'True'}, ('+','id'), (None,None)), ['3','4'])
1129         ae(filt(None, {a: 'False'}, ('+','id'), (None,None)), ['5'])
1130         ae(filt(None, {a: ['True']}, ('+','id'), (None,None)), ['3','4'])
1131         ae(filt(None, {a: ['False']}, ('+','id'), (None,None)), ['5'])
1132         ae(filt(None, {a: ['False','True']}, ('+','id'), (None,None)),
1133             ['3','4','5'])
1134         ae(filt(None, {a: True}, ('+','id'), (None,None)), ['3','4'])
1135         ae(filt(None, {a: False}, ('+','id'), (None,None)), ['5'])
1136         ae(filt(None, {a: 1}, ('+','id'), (None,None)), ['3','4'])
1137         ae(filt(None, {a: 0}, ('+','id'), (None,None)), ['5'])
1138         ae(filt(None, {a: [1]}, ('+','id'), (None,None)), ['3','4'])
1139         ae(filt(None, {a: [0]}, ('+','id'), (None,None)), ['5'])
1140         ae(filt(None, {a: [0,1]}, ('+','id'), (None,None)), ['3','4','5'])
1141         ae(filt(None, {a: [True]}, ('+','id'), (None,None)), ['3','4'])
1142         ae(filt(None, {a: [False]}, ('+','id'), (None,None)), ['5'])
1143         ae(filt(None, {a: [False,True]}, ('+','id'), (None,None)),
1144             ['3','4','5'])
1146     def testFilteringNumber(self):
1147         self.filteringSetup()
1148         ae, filt = self.assertEqual, self.db.user.filter
1149         ae(filt(None, {'age': '1'}, ('+','id'), (None,None)), ['3'])
1150         ae(filt(None, {'age': '1.5'}, ('+','id'), (None,None)), ['4'])
1151         ae(filt(None, {'age': '2'}, ('+','id'), (None,None)), ['5'])
1152         ae(filt(None, {'age': ['1','2']}, ('+','id'), (None,None)), ['3','5'])
1153         ae(filt(None, {'age': 2}, ('+','id'), (None,None)), ['5'])
1154         ae(filt(None, {'age': [1,2]}, ('+','id'), (None,None)), ['3','5'])
1156     def testFilteringString(self):
1157         ae, filt = self.filteringSetup()
1158         ae(filt(None, {'title': ['one']}, ('+','id'), (None,None)), ['1'])
1159         ae(filt(None, {'title': ['issue one']}, ('+','id'), (None,None)),
1160             ['1'])
1161         ae(filt(None, {'title': ['issue', 'one']}, ('+','id'), (None,None)),
1162             ['1'])
1163         ae(filt(None, {'title': ['issue']}, ('+','id'), (None,None)),
1164             ['1','2','3'])
1165         ae(filt(None, {'title': ['one', 'two']}, ('+','id'), (None,None)),
1166             [])
1168     def testFilteringLink(self):
1169         ae, filt = self.filteringSetup()
1170         ae(filt(None, {'status': '1'}, ('+','id'), (None,None)), ['2','3'])
1171         ae(filt(None, {'assignedto': '-1'}, ('+','id'), (None,None)), ['3','4'])
1172         ae(filt(None, {'assignedto': None}, ('+','id'), (None,None)), ['3','4'])
1173         ae(filt(None, {'assignedto': [None]}, ('+','id'), (None,None)),
1174             ['3','4'])
1175         ae(filt(None, {'assignedto': ['-1', None]}, ('+','id'), (None,None)),
1176             ['3','4'])
1177         ae(filt(None, {'assignedto': ['1', None]}, ('+','id'), (None,None)),
1178             ['1', '3','4'])
1180     def testFilteringMultilinkAndGroup(self):
1181         """testFilteringMultilinkAndGroup:
1182         See roundup Bug 1541128: apparently grouping by something and
1183         searching a Multilink failed with MySQL 5.0
1184         """
1185         ae, filt = self.filteringSetup()
1186         ae(filt(None, {'files': '1'}, ('-','activity'), ('+','status')), ['4'])
1188     def testFilteringRetired(self):
1189         ae, filt = self.filteringSetup()
1190         self.db.issue.retire('2')
1191         ae(filt(None, {'status': '1'}, ('+','id'), (None,None)), ['3'])
1193     def testFilteringMultilink(self):
1194         ae, filt = self.filteringSetup()
1195         ae(filt(None, {'nosy': '3'}, ('+','id'), (None,None)), ['4'])
1196         ae(filt(None, {'nosy': '-1'}, ('+','id'), (None,None)), ['1', '2'])
1197         ae(filt(None, {'nosy': ['1','2']}, ('+', 'status'),
1198             ('-', 'deadline')), ['4', '3'])
1200     def testFilteringMany(self):
1201         ae, filt = self.filteringSetup()
1202         ae(filt(None, {'nosy': '2', 'status': '1'}, ('+','id'), (None,None)),
1203             ['3'])
1205     def testFilteringRangeBasic(self):
1206         ae, filt = self.filteringSetup()
1207         ae(filt(None, {'deadline': 'from 2003-02-10 to 2003-02-23'}), ['1','3'])
1208         ae(filt(None, {'deadline': '2003-02-10; 2003-02-23'}), ['1','3'])
1209         ae(filt(None, {'deadline': '; 2003-02-16'}), ['2'])
1211     def testFilteringRangeTwoSyntaxes(self):
1212         ae, filt = self.filteringSetup()
1213         ae(filt(None, {'deadline': 'from 2003-02-16'}), ['1', '3', '4'])
1214         ae(filt(None, {'deadline': '2003-02-16;'}), ['1', '3', '4'])
1216     def testFilteringRangeYearMonthDay(self):
1217         ae, filt = self.filteringSetup()
1218         ae(filt(None, {'deadline': '2002'}), [])
1219         ae(filt(None, {'deadline': '2003'}), ['1', '2', '3'])
1220         ae(filt(None, {'deadline': '2004'}), ['4'])
1221         ae(filt(None, {'deadline': '2003-02-16'}), ['1'])
1222         ae(filt(None, {'deadline': '2003-02-17'}), [])
1224     def testFilteringRangeMonths(self):
1225         ae, filt = self.filteringSetup()
1226         for month in range(1, 13):
1227             for n in range(1, month+1):
1228                 i = self.db.issue.create(title='%d.%d'%(month, n),
1229                     deadline=date.Date('2001-%02d-%02d.00:00'%(month, n)))
1230         self.db.commit()
1232         for month in range(1, 13):
1233             r = filt(None, dict(deadline='2001-%02d'%month))
1234             assert len(r) == month, 'month %d != length %d'%(month, len(r))
1236     def testFilteringRangeInterval(self):
1237         ae, filt = self.filteringSetup()
1238         ae(filt(None, {'foo': 'from 0:50 to 2:00'}), ['1'])
1239         ae(filt(None, {'foo': 'from 0:50 to 1d 2:00'}), ['1', '2'])
1240         ae(filt(None, {'foo': 'from 5:50'}), ['2'])
1241         ae(filt(None, {'foo': 'to 0:05'}), [])
1243     def testFilteringRangeGeekInterval(self):
1244         ae, filt = self.filteringSetup()
1245         for issue in (
1246                 { 'deadline': date.Date('. -2d')},
1247                 { 'deadline': date.Date('. -1d')},
1248                 { 'deadline': date.Date('. -8d')},
1249                 ):
1250             self.db.issue.create(**issue)
1251         ae(filt(None, {'deadline': '-2d;'}), ['5', '6'])
1252         ae(filt(None, {'deadline': '-1d;'}), ['6'])
1253         ae(filt(None, {'deadline': '-1w;'}), ['5', '6'])
1255     def testFilteringIntervalSort(self):
1256         # 1: '1:10'
1257         # 2: '1d'
1258         # 3: None
1259         # 4: '0:10'
1260         ae, filt = self.filteringSetup()
1261         # ascending should sort None, 1:10, 1d
1262         ae(filt(None, {}, ('+','foo'), (None,None)), ['3', '4', '1', '2'])
1263         # descending should sort 1d, 1:10, None
1264         ae(filt(None, {}, ('-','foo'), (None,None)), ['2', '1', '4', '3'])
1266     def testFilteringStringSort(self):
1267         # 1: 'issue one'
1268         # 2: 'issue two'
1269         # 3: 'issue three'
1270         # 4: 'non four'
1271         ae, filt = self.filteringSetup()
1272         ae(filt(None, {}, ('+','title')), ['1', '3', '2', '4'])
1273         ae(filt(None, {}, ('-','title')), ['4', '2', '3', '1'])
1274         # Test string case: For now allow both, w/wo case matching.
1275         # 1: 'issue one'
1276         # 2: 'issue two'
1277         # 3: 'Issue three'
1278         # 4: 'non four'
1279         self.db.issue.set('3', title='Issue three')
1280         ae(filt(None, {}, ('+','title')), ['1', '3', '2', '4'])
1281         ae(filt(None, {}, ('-','title')), ['4', '2', '3', '1'])
1282         # Obscure bug in anydbm backend trying to convert to number
1283         # 1: '1st issue'
1284         # 2: '2'
1285         # 3: 'Issue three'
1286         # 4: 'non four'
1287         self.db.issue.set('1', title='1st issue')
1288         self.db.issue.set('2', title='2')
1289         ae(filt(None, {}, ('+','title')), ['1', '2', '3', '4'])
1290         ae(filt(None, {}, ('-','title')), ['4', '3', '2', '1'])
1292     def testFilteringMultilinkSort(self):
1293         # 1: []                 Reverse:  1: []
1294         # 2: []                           2: []
1295         # 3: ['admin','fred']             3: ['fred','admin']
1296         # 4: ['admin','bleep','fred']     4: ['fred','bleep','admin']
1297         # Note the sort order for the multilink doen't change when
1298         # reversing the sort direction due to the re-sorting of the
1299         # multilink!
1300         ae, filt = self.filteringSetup()
1301         ae(filt(None, {}, ('+','nosy'), (None,None)), ['1', '2', '4', '3'])
1302         ae(filt(None, {}, ('-','nosy'), (None,None)), ['4', '3', '1', '2'])
1304     def testFilteringMultilinkSortGroup(self):
1305         # 1: status: 2 "in-progress" nosy: []
1306         # 2: status: 1 "unread"      nosy: []
1307         # 3: status: 1 "unread"      nosy: ['admin','fred']
1308         # 4: status: 3 "testing"     nosy: ['admin','bleep','fred']
1309         ae, filt = self.filteringSetup()
1310         ae(filt(None, {}, ('+','nosy'), ('+','status')), ['1', '4', '2', '3'])
1311         ae(filt(None, {}, ('-','nosy'), ('+','status')), ['1', '4', '3', '2'])
1312         ae(filt(None, {}, ('+','nosy'), ('-','status')), ['2', '3', '4', '1'])
1313         ae(filt(None, {}, ('-','nosy'), ('-','status')), ['3', '2', '4', '1'])
1314         ae(filt(None, {}, ('+','status'), ('+','nosy')), ['1', '2', '4', '3'])
1315         ae(filt(None, {}, ('-','status'), ('+','nosy')), ['2', '1', '4', '3'])
1316         ae(filt(None, {}, ('+','status'), ('-','nosy')), ['4', '3', '1', '2'])
1317         ae(filt(None, {}, ('-','status'), ('-','nosy')), ['4', '3', '2', '1'])
1319     def testFilteringLinkSortGroup(self):
1320         # 1: status: 2 -> 'i', priority: 3 -> 1
1321         # 2: status: 1 -> 'u', priority: 3 -> 1
1322         # 3: status: 1 -> 'u', priority: 2 -> 3
1323         # 4: status: 3 -> 't', priority: 2 -> 3
1324         ae, filt = self.filteringSetup()
1325         ae(filt(None, {}, ('+','status'), ('+','priority')),
1326             ['1', '2', '4', '3'])
1327         ae(filt(None, {'priority':'2'}, ('+','status'), ('+','priority')),
1328             ['4', '3'])
1329         ae(filt(None, {'priority.order':'3'}, ('+','status'), ('+','priority')),
1330             ['4', '3'])
1331         ae(filt(None, {'priority':['2','3']}, ('+','priority'), ('+','status')),
1332             ['1', '4', '2', '3'])
1333         ae(filt(None, {}, ('+','priority'), ('+','status')),
1334             ['1', '4', '2', '3'])
1336     def testFilteringDateSort(self):
1337         # '1': '2003-02-16.22:50'
1338         # '2': '2003-01-01.00:00'
1339         # '3': '2003-02-18'
1340         # '4': '2004-03-08'
1341         ae, filt = self.filteringSetup()
1342         # ascending
1343         ae(filt(None, {}, ('+','deadline'), (None,None)), ['2', '1', '3', '4'])
1344         # descending
1345         ae(filt(None, {}, ('-','deadline'), (None,None)), ['4', '3', '1', '2'])
1347     def testFilteringDateSortPriorityGroup(self):
1348         # '1': '2003-02-16.22:50'  1 => 2
1349         # '2': '2003-01-01.00:00'  3 => 1
1350         # '3': '2003-02-18'        2 => 3
1351         # '4': '2004-03-08'        1 => 2
1352         ae, filt = self.filteringSetup()
1354         # ascending
1355         ae(filt(None, {}, ('+','deadline'), ('+','priority')),
1356             ['2', '1', '3', '4'])
1357         ae(filt(None, {}, ('-','deadline'), ('+','priority')),
1358             ['1', '2', '4', '3'])
1359         # descending
1360         ae(filt(None, {}, ('+','deadline'), ('-','priority')),
1361             ['3', '4', '2', '1'])
1362         ae(filt(None, {}, ('-','deadline'), ('-','priority')),
1363             ['4', '3', '1', '2'])
1365     def filteringSetupTransitiveSearch(self):
1366         u_m = {}
1367         k = 30
1368         for user in (
1369                 {'username': 'ceo', 'age': 129},
1370                 {'username': 'grouplead1', 'age': 29, 'supervisor': '3'},
1371                 {'username': 'grouplead2', 'age': 29, 'supervisor': '3'},
1372                 {'username': 'worker1', 'age': 25, 'supervisor' : '4'},
1373                 {'username': 'worker2', 'age': 24, 'supervisor' : '4'},
1374                 {'username': 'worker3', 'age': 23, 'supervisor' : '5'},
1375                 {'username': 'worker4', 'age': 22, 'supervisor' : '5'},
1376                 {'username': 'worker5', 'age': 21, 'supervisor' : '5'}):
1377             u = self.db.user.create(**user)
1378             u_m [u] = self.db.msg.create(author = u, content = ' '
1379                 , date = date.Date ('2006-01-%s' % k))
1380             k -= 1
1381         iss = self.db.issue
1382         for issue in (
1383                 {'title': 'ts1', 'status': '2', 'assignedto': '6',
1384                     'priority': '3', 'messages' : [u_m ['6']], 'nosy' : ['4']},
1385                 {'title': 'ts2', 'status': '1', 'assignedto': '6',
1386                     'priority': '3', 'messages' : [u_m ['6']], 'nosy' : ['5']},
1387                 {'title': 'ts4', 'status': '2', 'assignedto': '7',
1388                     'priority': '3', 'messages' : [u_m ['7']]},
1389                 {'title': 'ts5', 'status': '1', 'assignedto': '8',
1390                     'priority': '3', 'messages' : [u_m ['8']]},
1391                 {'title': 'ts6', 'status': '2', 'assignedto': '9',
1392                     'priority': '3', 'messages' : [u_m ['9']]},
1393                 {'title': 'ts7', 'status': '1', 'assignedto': '10',
1394                     'priority': '3', 'messages' : [u_m ['10']]},
1395                 {'title': 'ts8', 'status': '2', 'assignedto': '10',
1396                     'priority': '3', 'messages' : [u_m ['10']]},
1397                 {'title': 'ts9', 'status': '1', 'assignedto': '10',
1398                     'priority': '3', 'messages' : [u_m ['10'], u_m ['9']]}):
1399             self.db.issue.create(**issue)
1400         return self.assertEqual, self.db.issue.filter
1402     def testFilteringTransitiveLinkUser(self):
1403         ae, filt = self.filteringSetupTransitiveSearch()
1404         ufilt = self.db.user.filter
1405         ae(ufilt(None, {'supervisor.username': 'ceo'}, ('+','username')),
1406             ['4', '5'])
1407         ae(ufilt(None, {'supervisor.supervisor.username': 'ceo'},
1408             ('+','username')), ['6', '7', '8', '9', '10'])
1409         ae(ufilt(None, {'supervisor.supervisor': '3'}, ('+','username')),
1410             ['6', '7', '8', '9', '10'])
1411         ae(ufilt(None, {'supervisor.supervisor.id': '3'}, ('+','username')),
1412             ['6', '7', '8', '9', '10'])
1413         ae(ufilt(None, {'supervisor.username': 'grouplead1'}, ('+','username')),
1414             ['6', '7'])
1415         ae(ufilt(None, {'supervisor.username': 'grouplead2'}, ('+','username')),
1416             ['8', '9', '10'])
1417         ae(ufilt(None, {'supervisor.username': 'grouplead2',
1418             'supervisor.supervisor.username': 'ceo'}, ('+','username')),
1419             ['8', '9', '10'])
1420         ae(ufilt(None, {'supervisor.supervisor': '3', 'supervisor': '4'},
1421             ('+','username')), ['6', '7'])
1423     def testFilteringTransitiveLinkSort(self):
1424         ae, filt = self.filteringSetupTransitiveSearch()
1425         ufilt = self.db.user.filter
1426         # Need to make ceo his own (and first two users') supervisor,
1427         # otherwise we will depend on sorting order of NULL values.
1428         # Leave that to a separate test.
1429         self.db.user.set('1', supervisor = '3')
1430         self.db.user.set('2', supervisor = '3')
1431         self.db.user.set('3', supervisor = '3')
1432         ae(ufilt(None, {'supervisor':'3'}, []), ['1', '2', '3', '4', '5'])
1433         ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1434             ('+','supervisor.supervisor'), ('+','supervisor'),
1435             ('+','username')]),
1436             ['1', '3', '2', '4', '5', '6', '7', '8', '9', '10'])
1437         ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1438             ('-','supervisor.supervisor'), ('-','supervisor'),
1439             ('+','username')]),
1440             ['8', '9', '10', '6', '7', '1', '3', '2', '4', '5'])
1441         ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1442             ('+','assignedto.supervisor.supervisor'),
1443             ('+','assignedto.supervisor'), ('+','assignedto')]),
1444             ['1', '2', '3', '4', '5', '6', '7', '8'])
1445         ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1446             ('+','assignedto.supervisor.supervisor'),
1447             ('-','assignedto.supervisor'), ('+','assignedto')]),
1448             ['4', '5', '6', '7', '8', '1', '2', '3'])
1449         ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1450             ('+','assignedto.supervisor.supervisor'),
1451             ('+','assignedto.supervisor'), ('+','assignedto'),
1452             ('-','status')]),
1453             ['2', '1', '3', '4', '5', '6', '8', '7'])
1454         ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1455             ('+','assignedto.supervisor.supervisor'),
1456             ('+','assignedto.supervisor'), ('+','assignedto'),
1457             ('+','status')]),
1458             ['1', '2', '3', '4', '5', '7', '6', '8'])
1459         ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1460             ('+','assignedto.supervisor.supervisor'),
1461             ('-','assignedto.supervisor'), ('+','assignedto'), ('+','status')]),
1462             ['4', '5', '7', '6', '8', '1', '2', '3'])
1463         ae(filt(None, {'assignedto':['6','7','8','9','10']},
1464             [('+','assignedto.supervisor.supervisor.supervisor'),
1465             ('+','assignedto.supervisor.supervisor'),
1466             ('-','assignedto.supervisor'), ('+','assignedto'), ('+','status')]),
1467             ['4', '5', '7', '6', '8', '1', '2', '3'])
1468         ae(filt(None, {'assignedto':['6','7','8','9']},
1469             [('+','assignedto.supervisor.supervisor.supervisor'),
1470             ('+','assignedto.supervisor.supervisor'),
1471             ('-','assignedto.supervisor'), ('+','assignedto'), ('+','status')]),
1472             ['4', '5', '1', '2', '3'])
1474     def testFilteringTransitiveLinkSortNull(self):
1475         """Check sorting of NULL values"""
1476         ae, filt = self.filteringSetupTransitiveSearch()
1477         ufilt = self.db.user.filter
1478         ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1479             ('+','supervisor.supervisor'), ('+','supervisor'),
1480             ('+','username')]),
1481             ['1', '3', '2', '4', '5', '6', '7', '8', '9', '10'])
1482         ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1483             ('-','supervisor.supervisor'), ('-','supervisor'),
1484             ('+','username')]),
1485             ['8', '9', '10', '6', '7', '4', '5', '1', '3', '2'])
1486         ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1487             ('+','assignedto.supervisor.supervisor'),
1488             ('+','assignedto.supervisor'), ('+','assignedto')]),
1489             ['1', '2', '3', '4', '5', '6', '7', '8'])
1490         ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1491             ('+','assignedto.supervisor.supervisor'),
1492             ('-','assignedto.supervisor'), ('+','assignedto')]),
1493             ['4', '5', '6', '7', '8', '1', '2', '3'])
1495     def testFilteringTransitiveLinkIssue(self):
1496         ae, filt = self.filteringSetupTransitiveSearch()
1497         ae(filt(None, {'assignedto.supervisor.username': 'grouplead1'},
1498             ('+','id')), ['1', '2', '3'])
1499         ae(filt(None, {'assignedto.supervisor.username': 'grouplead2'},
1500             ('+','id')), ['4', '5', '6', '7', '8'])
1501         ae(filt(None, {'assignedto.supervisor.username': 'grouplead2',
1502                        'status': '1'}, ('+','id')), ['4', '6', '8'])
1503         ae(filt(None, {'assignedto.supervisor.username': 'grouplead2',
1504                        'status': '2'}, ('+','id')), ['5', '7'])
1505         ae(filt(None, {'assignedto.supervisor.username': ['grouplead2'],
1506                        'status': '2'}, ('+','id')), ['5', '7'])
1507         ae(filt(None, {'assignedto.supervisor': ['4', '5'], 'status': '2'},
1508             ('+','id')), ['1', '3', '5', '7'])
1510     def testFilteringTransitiveMultilink(self):
1511         ae, filt = self.filteringSetupTransitiveSearch()
1512         ae(filt(None, {'messages.author.username': 'grouplead1'},
1513             ('+','id')), [])
1514         ae(filt(None, {'messages.author': '6'},
1515             ('+','id')), ['1', '2'])
1516         ae(filt(None, {'messages.author.id': '6'},
1517             ('+','id')), ['1', '2'])
1518         ae(filt(None, {'messages.author.username': 'worker1'},
1519             ('+','id')), ['1', '2'])
1520         ae(filt(None, {'messages.author': '10'},
1521             ('+','id')), ['6', '7', '8'])
1522         ae(filt(None, {'messages.author': '9'},
1523             ('+','id')), ['5', '8'])
1524         ae(filt(None, {'messages.author': ['9', '10']},
1525             ('+','id')), ['5', '6', '7', '8'])
1526         ae(filt(None, {'messages.author': ['8', '9']},
1527             ('+','id')), ['4', '5', '8'])
1528         ae(filt(None, {'messages.author': ['8', '9'], 'status' : '1'},
1529             ('+','id')), ['4', '8'])
1530         ae(filt(None, {'messages.author': ['8', '9'], 'status' : '2'},
1531             ('+','id')), ['5'])
1532         ae(filt(None, {'messages.author': ['8', '9', '10'],
1533             'messages.date': '2006-01-22.21:00;2006-01-23'}, ('+','id')),
1534             ['6', '7', '8'])
1535         ae(filt(None, {'nosy.supervisor.username': 'ceo'},
1536             ('+','id')), ['1', '2'])
1537         ae(filt(None, {'messages.author': ['6', '9']},
1538             ('+','id')), ['1', '2', '5', '8'])
1539         ae(filt(None, {'messages': ['5', '7']},
1540             ('+','id')), ['3', '5', '8'])
1541         ae(filt(None, {'messages.author': ['6', '9'], 'messages': ['5', '7']},
1542             ('+','id')), ['5', '8'])
1544     def testFilteringTransitiveMultilinkSort(self):
1545         ae, filt = self.filteringSetupTransitiveSearch()
1546         ae(filt(None, {}, [('+','messages.author')]),
1547             ['1', '2', '3', '4', '5', '8', '6', '7'])
1548         ae(filt(None, {}, [('-','messages.author')]),
1549             ['8', '6', '7', '5', '4', '3', '1', '2'])
1550         ae(filt(None, {}, [('+','messages.date')]),
1551             ['6', '7', '8', '5', '4', '3', '1', '2'])
1552         ae(filt(None, {}, [('-','messages.date')]),
1553             ['1', '2', '3', '4', '8', '5', '6', '7'])
1554         ae(filt(None, {}, [('+','messages.author'),('+','messages.date')]),
1555             ['1', '2', '3', '4', '5', '8', '6', '7'])
1556         ae(filt(None, {}, [('-','messages.author'),('+','messages.date')]),
1557             ['8', '6', '7', '5', '4', '3', '1', '2'])
1558         ae(filt(None, {}, [('+','messages.author'),('-','messages.date')]),
1559             ['1', '2', '3', '4', '5', '8', '6', '7'])
1560         ae(filt(None, {}, [('-','messages.author'),('-','messages.date')]),
1561             ['8', '6', '7', '5', '4', '3', '1', '2'])
1562         ae(filt(None, {}, [('+','messages.author'),('+','assignedto')]),
1563             ['1', '2', '3', '4', '5', '8', '6', '7'])
1564         ae(filt(None, {}, [('+','messages.author'),
1565             ('-','assignedto.supervisor'),('-','assignedto')]),
1566             ['1', '2', '3', '4', '5', '8', '6', '7'])
1567         ae(filt(None, {},
1568             [('+','messages.author.supervisor.supervisor.supervisor'),
1569             ('+','messages.author.supervisor.supervisor'),
1570             ('+','messages.author.supervisor'), ('+','messages.author')]),
1571             ['1', '2', '3', '4', '5', '6', '7', '8'])
1572         self.db.user.setorderprop('age')
1573         self.db.msg.setorderprop('date')
1574         ae(filt(None, {}, [('+','messages'), ('+','messages.author')]),
1575             ['6', '7', '8', '5', '4', '3', '1', '2'])
1576         ae(filt(None, {}, [('+','messages.author'), ('+','messages')]),
1577             ['6', '7', '8', '5', '4', '3', '1', '2'])
1578         self.db.msg.setorderprop('author')
1579         # Orderprop is a Link/Multilink:
1580         # messages are sorted by orderprop().labelprop(), i.e. by
1581         # author.username, *not* by author.orderprop() (author.age)!
1582         ae(filt(None, {}, [('+','messages')]),
1583             ['1', '2', '3', '4', '5', '8', '6', '7'])
1584         ae(filt(None, {}, [('+','messages.author'), ('+','messages')]),
1585             ['6', '7', '8', '5', '4', '3', '1', '2'])
1586         # The following will sort by
1587         # author.supervisor.username and then by
1588         # author.username
1589         # I've resited the tempation to implement recursive orderprop
1590         # here: There could even be loops if several classes specify a
1591         # Link or Multilink as the orderprop...
1592         # msg: 4: worker1 (id  5) : grouplead1 (id 4) ceo (id 3)
1593         # msg: 5: worker2 (id  7) : grouplead1 (id 4) ceo (id 3)
1594         # msg: 6: worker3 (id  8) : grouplead2 (id 5) ceo (id 3)
1595         # msg: 7: worker4 (id  9) : grouplead2 (id 5) ceo (id 3)
1596         # msg: 8: worker5 (id 10) : grouplead2 (id 5) ceo (id 3)
1597         # issue 1: messages 4   sortkey:[[grouplead1], [worker1], 1]
1598         # issue 2: messages 4   sortkey:[[grouplead1], [worker1], 2]
1599         # issue 3: messages 5   sortkey:[[grouplead1], [worker2], 3]
1600         # issue 4: messages 6   sortkey:[[grouplead2], [worker3], 4]
1601         # issue 5: messages 7   sortkey:[[grouplead2], [worker4], 5]
1602         # issue 6: messages 8   sortkey:[[grouplead2], [worker5], 6]
1603         # issue 7: messages 8   sortkey:[[grouplead2], [worker5], 7]
1604         # issue 8: messages 7,8 sortkey:[[grouplead2, grouplead2], ...]
1605         self.db.user.setorderprop('supervisor')
1606         ae(filt(None, {}, [('+','messages.author'), ('-','messages')]),
1607             ['3', '1', '2', '6', '7', '5', '4', '8'])
1609     def testFilteringSortId(self):
1610         ae, filt = self.filteringSetupTransitiveSearch()
1611         ae(self.db.user.filter(None, {}, ('+','id')),
1612             ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])
1614 # XXX add sorting tests for other types
1616     # nuke and re-create db for restore
1617     def nukeAndCreate(self):
1618         # shut down this db and nuke it
1619         self.db.close()
1620         self.nuke_database()
1622         # open a new, empty database
1623         os.makedirs(config.DATABASE + '/files')
1624         self.db = self.module.Database(config, 'admin')
1625         setupSchema(self.db, 0, self.module)
1627     def testImportExport(self):
1628         # use the filtering setup to create a bunch of items
1629         ae, filt = self.filteringSetup()
1630         # Get some stuff into the journal for testing import/export of
1631         # journal data:
1632         self.db.user.set('4', password = password.Password('xyzzy'))
1633         self.db.user.set('4', age = 3)
1634         self.db.user.set('4', assignable = True)
1635         self.db.issue.set('1', title = 'i1', status = '3')
1636         self.db.issue.set('1', deadline = date.Date('2007'))
1637         self.db.issue.set('1', foo = date.Interval('1:20'))
1638         p = self.db.priority.create(name = 'some_prio_without_order')
1639         self.db.commit()
1640         self.db.user.set('4', password = password.Password('123xyzzy'))
1641         self.db.user.set('4', assignable = False)
1642         self.db.priority.set(p, order = '4711')
1643         self.db.commit()
1645         self.db.user.retire('3')
1646         self.db.issue.retire('2')
1648         # grab snapshot of the current database
1649         orig = {}
1650         origj = {}
1651         for cn,klass in self.db.classes.items():
1652             cl = orig[cn] = {}
1653             jn = origj[cn] = {}
1654             for id in klass.list():
1655                 it = cl[id] = {}
1656                 jn[id] = self.db.getjournal(cn, id)
1657                 for name in klass.getprops().keys():
1658                     it[name] = klass.get(id, name)
1660         os.mkdir('_test_export')
1661         try:
1662             # grab the export
1663             export = {}
1664             journals = {}
1665             for cn,klass in self.db.classes.items():
1666                 names = klass.export_propnames()
1667                 cl = export[cn] = [names+['is retired']]
1668                 for id in klass.getnodeids():
1669                     cl.append(klass.export_list(names, id))
1670                     if hasattr(klass, 'export_files'):
1671                         klass.export_files('_test_export', id)
1672                 journals[cn] = klass.export_journals()
1674             self.nukeAndCreate()
1676             # import
1677             for cn, items in export.items():
1678                 klass = self.db.classes[cn]
1679                 names = items[0]
1680                 maxid = 1
1681                 for itemprops in items[1:]:
1682                     id = int(klass.import_list(names, itemprops))
1683                     if hasattr(klass, 'import_files'):
1684                         klass.import_files('_test_export', str(id))
1685                     maxid = max(maxid, id)
1686                 self.db.setid(cn, str(maxid+1))
1687                 klass.import_journals(journals[cn])
1688             # This is needed, otherwise journals won't be there for anydbm
1689             self.db.commit()
1690         finally:
1691             shutil.rmtree('_test_export')
1693         # compare with snapshot of the database
1694         for cn, items in orig.iteritems():
1695             klass = self.db.classes[cn]
1696             propdefs = klass.getprops(1)
1697             # ensure retired items are retired :)
1698             l = items.keys(); l.sort()
1699             m = klass.list(); m.sort()
1700             ae(l, m, '%s id list wrong %r vs. %r'%(cn, l, m))
1701             for id, props in items.items():
1702                 for name, value in props.items():
1703                     l = klass.get(id, name)
1704                     if isinstance(value, type([])):
1705                         value.sort()
1706                         l.sort()
1707                     try:
1708                         ae(l, value)
1709                     except AssertionError:
1710                         if not isinstance(propdefs[name], Date):
1711                             raise
1712                         # don't get hung up on rounding errors
1713                         assert not l.__cmp__(value, int_seconds=1)
1714         for jc, items in origj.iteritems():
1715             for id, oj in items.iteritems():
1716                 rj = self.db.getjournal(jc, id)
1717                 # Both mysql and postgresql have some minor issues with
1718                 # rounded seconds on export/import, so we compare only
1719                 # the integer part.
1720                 for j in oj:
1721                     j[1].second = float(int(j[1].second))
1722                 for j in rj:
1723                     j[1].second = float(int(j[1].second))
1724                 oj.sort()
1725                 rj.sort()
1726                 ae(oj, rj)
1728         # make sure the retired items are actually imported
1729         ae(self.db.user.get('4', 'username'), 'blop')
1730         ae(self.db.issue.get('2', 'title'), 'issue two')
1732         # make sure id counters are set correctly
1733         maxid = max([int(id) for id in self.db.user.list()])
1734         newid = self.db.user.create(username='testing')
1735         assert newid > maxid
1737     # test import/export via admin interface
1738     def testAdminImportExport(self):
1739         import roundup.admin
1740         import csv
1741         # use the filtering setup to create a bunch of items
1742         ae, filt = self.filteringSetup()
1743         # create large field
1744         self.db.priority.create(name = 'X' * 500)
1745         self.db.config.CSV_FIELD_SIZE = 400
1746         self.db.commit()
1747         output = []
1748         # ugly hack to get stderr output and disable stdout output
1749         # during regression test. Depends on roundup.admin not using
1750         # anything but stdout/stderr from sys (which is currently the
1751         # case)
1752         def stderrwrite(s):
1753             output.append(s)
1754         roundup.admin.sys = MockNull ()
1755         try:
1756             roundup.admin.sys.stderr.write = stderrwrite
1757             tool = roundup.admin.AdminTool()
1758             home = '.'
1759             tool.tracker_home = home
1760             tool.db = self.db
1761             tool.verbose = False
1762             tool.do_export (['_test_export'])
1763             self.assertEqual(len(output), 2)
1764             self.assertEqual(output [1], '\n')
1765             self.failUnless(output [0].startswith
1766                 ('Warning: config csv_field_size should be at least'))
1767             self.failUnless(int(output[0].split()[-1]) > 500)
1769             if hasattr(roundup.admin.csv, 'field_size_limit'):
1770                 self.nukeAndCreate()
1771                 self.db.config.CSV_FIELD_SIZE = 400
1772                 tool = roundup.admin.AdminTool()
1773                 tool.tracker_home = home
1774                 tool.db = self.db
1775                 tool.verbose = False
1776                 self.assertRaises(csv.Error, tool.do_import, ['_test_export'])
1778             self.nukeAndCreate()
1779             self.db.config.CSV_FIELD_SIZE = 3200
1780             tool = roundup.admin.AdminTool()
1781             tool.tracker_home = home
1782             tool.db = self.db
1783             tool.verbose = False
1784             tool.do_import(['_test_export'])
1785         finally:
1786             roundup.admin.sys = sys
1787             shutil.rmtree('_test_export')
1789     def testAddProperty(self):
1790         self.db.issue.create(title="spam", status='1')
1791         self.db.commit()
1793         self.db.issue.addprop(fixer=Link("user"))
1794         # force any post-init stuff to happen
1795         self.db.post_init()
1796         props = self.db.issue.getprops()
1797         keys = props.keys()
1798         keys.sort()
1799         self.assertEqual(keys, ['activity', 'actor', 'assignedto', 'creation',
1800             'creator', 'deadline', 'feedback', 'files', 'fixer', 'foo', 'id', 'messages',
1801             'nosy', 'priority', 'spam', 'status', 'superseder', 'title'])
1802         self.assertEqual(self.db.issue.get('1', "fixer"), None)
1804     def testRemoveProperty(self):
1805         self.db.issue.create(title="spam", status='1')
1806         self.db.commit()
1808         del self.db.issue.properties['title']
1809         self.db.post_init()
1810         props = self.db.issue.getprops()
1811         keys = props.keys()
1812         keys.sort()
1813         self.assertEqual(keys, ['activity', 'actor', 'assignedto', 'creation',
1814             'creator', 'deadline', 'feedback', 'files', 'foo', 'id', 'messages',
1815             'nosy', 'priority', 'spam', 'status', 'superseder'])
1816         self.assertEqual(self.db.issue.list(), ['1'])
1818     def testAddRemoveProperty(self):
1819         self.db.issue.create(title="spam", status='1')
1820         self.db.commit()
1822         self.db.issue.addprop(fixer=Link("user"))
1823         del self.db.issue.properties['title']
1824         self.db.post_init()
1825         props = self.db.issue.getprops()
1826         keys = props.keys()
1827         keys.sort()
1828         self.assertEqual(keys, ['activity', 'actor', 'assignedto', 'creation',
1829             'creator', 'deadline', 'feedback', 'files', 'fixer', 'foo', 'id',
1830             'messages', 'nosy', 'priority', 'spam', 'status', 'superseder'])
1831         self.assertEqual(self.db.issue.list(), ['1'])
1833     def testNosyMail(self) :
1834         """Creates one issue with two attachments, one smaller and one larger
1835            than the set max_attachment_size.
1836         """
1837         db = self.db
1838         db.config.NOSY_MAX_ATTACHMENT_SIZE = 4096
1839         res = dict(mail_to = None, mail_msg = None)
1840         def dummy_snd(s, to, msg, res=res) :
1841             res["mail_to"], res["mail_msg"] = to, msg
1842         backup, Mailer.smtp_send = Mailer.smtp_send, dummy_snd
1843         try :
1844             f1 = db.file.create(name="test1.txt", content="x" * 20)
1845             f2 = db.file.create(name="test2.txt", content="y" * 5000)
1846             m  = db.msg.create(content="one two", author="admin",
1847                 files = [f1, f2])
1848             i  = db.issue.create(title='spam', files = [f1, f2],
1849                 messages = [m], nosy = [db.user.lookup("fred")])
1851             db.issue.nosymessage(i, m, {})
1852             mail_msg = str(res["mail_msg"])
1853             self.assertEqual(res["mail_to"], ["fred@example.com"])
1854             self.assert_("From: admin" in mail_msg)
1855             self.assert_("Subject: [issue1] spam" in mail_msg)
1856             self.assert_("New submission from admin" in mail_msg)
1857             self.assert_("one two" in mail_msg)
1858             self.assert_("File 'test1.txt' not attached" not in mail_msg)
1859             self.assert_(base64.encodestring("xxx").rstrip() in mail_msg)
1860             self.assert_("File 'test2.txt' not attached" in mail_msg)
1861             self.assert_(base64.encodestring("yyy").rstrip() not in mail_msg)
1862         finally :
1863             Mailer.smtp_send = backup
1865 class ROTest(MyTestCase):
1866     def setUp(self):
1867         # remove previous test, ignore errors
1868         if os.path.exists(config.DATABASE):
1869             shutil.rmtree(config.DATABASE)
1870         os.makedirs(config.DATABASE + '/files')
1871         self.db = self.module.Database(config, 'admin')
1872         setupSchema(self.db, 1, self.module)
1873         self.db.close()
1875         self.db = self.module.Database(config)
1876         setupSchema(self.db, 0, self.module)
1878     def testExceptions(self):
1879         # this tests the exceptions that should be raised
1880         ar = self.assertRaises
1882         # this tests the exceptions that should be raised
1883         ar(DatabaseError, self.db.status.create, name="foo")
1884         ar(DatabaseError, self.db.status.set, '1', name="foo")
1885         ar(DatabaseError, self.db.status.retire, '1')
1888 class SchemaTest(MyTestCase):
1889     def setUp(self):
1890         # remove previous test, ignore errors
1891         if os.path.exists(config.DATABASE):
1892             shutil.rmtree(config.DATABASE)
1893         os.makedirs(config.DATABASE + '/files')
1895     def open_database(self):
1896         self.db = self.module.Database(config, 'admin')
1898     def test_reservedProperties(self):
1899         self.open_database()
1900         self.assertRaises(ValueError, self.module.Class, self.db, "a",
1901             creation=String())
1902         self.assertRaises(ValueError, self.module.Class, self.db, "a",
1903             activity=String())
1904         self.assertRaises(ValueError, self.module.Class, self.db, "a",
1905             creator=String())
1906         self.assertRaises(ValueError, self.module.Class, self.db, "a",
1907             actor=String())
1909     def init_a(self):
1910         self.open_database()
1911         a = self.module.Class(self.db, "a", name=String())
1912         a.setkey("name")
1913         self.db.post_init()
1915     def test_fileClassProps(self):
1916         self.open_database()
1917         a = self.module.FileClass(self.db, 'a')
1918         l = a.getprops().keys()
1919         l.sort()
1920         self.assert_(l, ['activity', 'actor', 'content', 'created',
1921             'creation', 'type'])
1923     def init_ab(self):
1924         self.open_database()
1925         a = self.module.Class(self.db, "a", name=String())
1926         a.setkey("name")
1927         b = self.module.Class(self.db, "b", name=String(),
1928             fooz=Multilink('a'))
1929         b.setkey("name")
1930         self.db.post_init()
1932     def test_addNewClass(self):
1933         self.init_a()
1935         self.assertRaises(ValueError, self.module.Class, self.db, "a",
1936             name=String())
1938         aid = self.db.a.create(name='apple')
1939         self.db.commit(); self.db.close()
1941         # add a new class to the schema and check creation of new items
1942         # (and existence of old ones)
1943         self.init_ab()
1944         bid = self.db.b.create(name='bear', fooz=[aid])
1945         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
1946         self.db.commit()
1947         self.db.close()
1949         # now check we can recall the added class' items
1950         self.init_ab()
1951         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
1952         self.assertEqual(self.db.a.lookup('apple'), aid)
1953         self.assertEqual(self.db.b.get(bid, 'name'), 'bear')
1954         self.assertEqual(self.db.b.get(bid, 'fooz'), [aid])
1955         self.assertEqual(self.db.b.lookup('bear'), bid)
1957         # confirm journal's ok
1958         self.db.getjournal('a', aid)
1959         self.db.getjournal('b', bid)
1961     def init_amod(self):
1962         self.open_database()
1963         a = self.module.Class(self.db, "a", name=String(), newstr=String(),
1964             newint=Interval(), newnum=Number(), newbool=Boolean(),
1965             newdate=Date())
1966         a.setkey("name")
1967         b = self.module.Class(self.db, "b", name=String())
1968         b.setkey("name")
1969         self.db.post_init()
1971     def test_modifyClass(self):
1972         self.init_ab()
1974         # add item to user and issue class
1975         aid = self.db.a.create(name='apple')
1976         bid = self.db.b.create(name='bear')
1977         self.db.commit(); self.db.close()
1979         # modify "a" schema
1980         self.init_amod()
1981         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
1982         self.assertEqual(self.db.a.get(aid, 'newstr'), None)
1983         self.assertEqual(self.db.a.get(aid, 'newint'), None)
1984         # hack - metakit can't return None for missing values, and we're not
1985         # really checking for that behavior here anyway
1986         self.assert_(not self.db.a.get(aid, 'newnum'))
1987         self.assert_(not self.db.a.get(aid, 'newbool'))
1988         self.assertEqual(self.db.a.get(aid, 'newdate'), None)
1989         self.assertEqual(self.db.b.get(aid, 'name'), 'bear')
1990         aid2 = self.db.a.create(name='aardvark', newstr='booz')
1991         self.db.commit(); self.db.close()
1993         # test
1994         self.init_amod()
1995         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
1996         self.assertEqual(self.db.a.get(aid, 'newstr'), None)
1997         self.assertEqual(self.db.b.get(aid, 'name'), 'bear')
1998         self.assertEqual(self.db.a.get(aid2, 'name'), 'aardvark')
1999         self.assertEqual(self.db.a.get(aid2, 'newstr'), 'booz')
2001         # confirm journal's ok
2002         self.db.getjournal('a', aid)
2003         self.db.getjournal('a', aid2)
2005     def init_amodkey(self):
2006         self.open_database()
2007         a = self.module.Class(self.db, "a", name=String(), newstr=String())
2008         a.setkey("newstr")
2009         b = self.module.Class(self.db, "b", name=String())
2010         b.setkey("name")
2011         self.db.post_init()
2013     def test_changeClassKey(self):
2014         self.init_amod()
2015         aid = self.db.a.create(name='apple')
2016         self.assertEqual(self.db.a.lookup('apple'), aid)
2017         self.db.commit(); self.db.close()
2019         # change the key to newstr on a
2020         self.init_amodkey()
2021         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
2022         self.assertEqual(self.db.a.get(aid, 'newstr'), None)
2023         self.assertRaises(KeyError, self.db.a.lookup, 'apple')
2024         aid2 = self.db.a.create(name='aardvark', newstr='booz')
2025         self.db.commit(); self.db.close()
2027         # check
2028         self.init_amodkey()
2029         self.assertEqual(self.db.a.lookup('booz'), aid2)
2031         # confirm journal's ok
2032         self.db.getjournal('a', aid)
2034     def test_removeClassKey(self):
2035         self.init_amod()
2036         aid = self.db.a.create(name='apple')
2037         self.assertEqual(self.db.a.lookup('apple'), aid)
2038         self.db.commit(); self.db.close()
2040         self.db = self.module.Database(config, 'admin')
2041         a = self.module.Class(self.db, "a", name=String(), newstr=String())
2042         self.db.post_init()
2044         aid2 = self.db.a.create(name='apple', newstr='booz')
2045         self.db.commit()
2048     def init_amodml(self):
2049         self.open_database()
2050         a = self.module.Class(self.db, "a", name=String(),
2051             newml=Multilink('a'))
2052         a.setkey('name')
2053         self.db.post_init()
2055     def test_makeNewMultilink(self):
2056         self.init_a()
2057         aid = self.db.a.create(name='apple')
2058         self.assertEqual(self.db.a.lookup('apple'), aid)
2059         self.db.commit(); self.db.close()
2061         # add a multilink prop
2062         self.init_amodml()
2063         bid = self.db.a.create(name='bear', newml=[aid])
2064         self.assertEqual(self.db.a.find(newml=aid), [bid])
2065         self.assertEqual(self.db.a.lookup('apple'), aid)
2066         self.db.commit(); self.db.close()
2068         # check
2069         self.init_amodml()
2070         self.assertEqual(self.db.a.find(newml=aid), [bid])
2071         self.assertEqual(self.db.a.lookup('apple'), aid)
2072         self.assertEqual(self.db.a.lookup('bear'), bid)
2074         # confirm journal's ok
2075         self.db.getjournal('a', aid)
2076         self.db.getjournal('a', bid)
2078     def test_removeMultilink(self):
2079         # add a multilink prop
2080         self.init_amodml()
2081         aid = self.db.a.create(name='apple')
2082         bid = self.db.a.create(name='bear', newml=[aid])
2083         self.assertEqual(self.db.a.find(newml=aid), [bid])
2084         self.assertEqual(self.db.a.lookup('apple'), aid)
2085         self.assertEqual(self.db.a.lookup('bear'), bid)
2086         self.db.commit(); self.db.close()
2088         # remove the multilink
2089         self.init_a()
2090         self.assertEqual(self.db.a.lookup('apple'), aid)
2091         self.assertEqual(self.db.a.lookup('bear'), bid)
2093         # confirm journal's ok
2094         self.db.getjournal('a', aid)
2095         self.db.getjournal('a', bid)
2097     def test_removeClass(self):
2098         self.init_ab()
2099         aid = self.db.a.create(name='apple')
2100         bid = self.db.b.create(name='bear')
2101         self.db.commit(); self.db.close()
2103         # drop the b class
2104         self.init_a()
2105         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
2106         self.assertEqual(self.db.a.lookup('apple'), aid)
2107         self.db.commit(); self.db.close()
2109         # now check we can recall the added class' items
2110         self.init_a()
2111         self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
2112         self.assertEqual(self.db.a.lookup('apple'), aid)
2114         # confirm journal's ok
2115         self.db.getjournal('a', aid)
2117 class RDBMSTest:
2118     """ tests specific to RDBMS backends """
2119     def test_indexTest(self):
2120         self.assertEqual(self.db.sql_index_exists('_issue', '_issue_id_idx'), 1)
2121         self.assertEqual(self.db.sql_index_exists('_issue', '_issue_x_idx'), 0)
2124 class ClassicInitTest(unittest.TestCase):
2125     count = 0
2126     db = None
2128     def setUp(self):
2129         ClassicInitTest.count = ClassicInitTest.count + 1
2130         self.dirname = '_test_init_%s'%self.count
2131         try:
2132             shutil.rmtree(self.dirname)
2133         except OSError, error:
2134             if error.errno not in (errno.ENOENT, errno.ESRCH): raise
2136     def testCreation(self):
2137         ae = self.assertEqual
2139         # set up and open a tracker
2140         tracker = setupTracker(self.dirname, self.backend)
2141         # open the database
2142         db = self.db = tracker.open('test')
2144         # check the basics of the schema and initial data set
2145         l = db.priority.list()
2146         l.sort()
2147         ae(l, ['1', '2', '3', '4', '5'])
2148         l = db.status.list()
2149         l.sort()
2150         ae(l, ['1', '2', '3', '4', '5', '6', '7', '8'])
2151         l = db.keyword.list()
2152         ae(l, [])
2153         l = db.user.list()
2154         l.sort()
2155         ae(l, ['1', '2'])
2156         l = db.msg.list()
2157         ae(l, [])
2158         l = db.file.list()
2159         ae(l, [])
2160         l = db.issue.list()
2161         ae(l, [])
2163     def tearDown(self):
2164         if self.db is not None:
2165             self.db.close()
2166         try:
2167             shutil.rmtree(self.dirname)
2168         except OSError, error:
2169             if error.errno not in (errno.ENOENT, errno.ESRCH): raise
2171 # vim: set et sts=4 sw=4 :