94d34d333960e28c197ff282518bfb7217f29950
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, sets, base64, os.path
22 from roundup.hyperdb import String, Password, Link, Multilink, Date, \
23 Interval, DatabaseError, Boolean, Number, Node
24 from roundup.mailer import Mailer
25 from roundup import date, password, init, instance, configuration, support
27 from mocknull import MockNull
29 config = configuration.CoreConfig()
30 config.DATABASE = "db"
31 config.RDBMS_NAME = "rounduptest"
32 config.RDBMS_HOST = "localhost"
33 config.RDBMS_USER = "rounduptest"
34 config.RDBMS_PASSWORD = "rounduptest"
35 #config.logging = MockNull()
36 # these TRACKER_WEB and MAIL_DOMAIN values are used in mailgw tests
37 config.MAIL_DOMAIN = "your.tracker.email.domain.example"
38 config.TRACKER_WEB = "http://tracker.example/cgi-bin/roundup.cgi/bugs/"
39 # uncomment the following to have excessive debug output from test cases
40 # FIXME: tracker logging level should be increased by -v arguments
41 # to 'run_tests.py' script
42 #config.LOGGING_FILENAME = "/tmp/logfile"
43 #config.LOGGING_LEVEL = "DEBUG"
44 config.init_logging()
46 def setupTracker(dirname, backend="anydbm"):
47 """Install and initialize new tracker in dirname; return tracker instance.
49 If the directory exists, it is wiped out before the operation.
51 """
52 global config
53 try:
54 shutil.rmtree(dirname)
55 except OSError, error:
56 if error.errno not in (errno.ENOENT, errno.ESRCH): raise
57 # create the instance
58 init.install(dirname, os.path.join(os.path.dirname(__file__),
59 '..',
60 'share',
61 'roundup',
62 'templates',
63 'classic'))
64 init.write_select_db(dirname, backend)
65 config.save(os.path.join(dirname, 'config.ini'))
66 tracker = instance.open(dirname)
67 if tracker.exists():
68 tracker.nuke()
69 init.write_select_db(dirname, backend)
70 tracker.init(password.Password('sekrit'))
71 return tracker
73 def setupSchema(db, create, module):
74 status = module.Class(db, "status", name=String())
75 status.setkey("name")
76 priority = module.Class(db, "priority", name=String(), order=String())
77 priority.setkey("name")
78 user = module.Class(db, "user", username=String(), password=Password(),
79 assignable=Boolean(), age=Number(), roles=String(), address=String(),
80 supervisor=Link('user'),realname=String())
81 user.setkey("username")
82 file = module.FileClass(db, "file", name=String(), type=String(),
83 comment=String(indexme="yes"), fooz=Password())
84 file_nidx = module.FileClass(db, "file_nidx", content=String(indexme='no'))
85 issue = module.IssueClass(db, "issue", title=String(indexme="yes"),
86 status=Link("status"), nosy=Multilink("user"), deadline=Date(),
87 foo=Interval(), files=Multilink("file"), assignedto=Link('user'),
88 priority=Link('priority'), spam=Multilink('msg'),
89 feedback=Link('msg'))
90 stuff = module.Class(db, "stuff", stuff=String())
91 session = module.Class(db, 'session', title=String())
92 msg = module.FileClass(db, "msg", date=Date(),
93 author=Link("user", do_journal='no'),
94 files=Multilink('file'), inreplyto=String(),
95 messageid=String(),
96 recipients=Multilink("user", do_journal='no')
97 )
98 session.disableJournalling()
99 db.post_init()
100 if create:
101 user.create(username="admin", roles='Admin',
102 password=password.Password('sekrit'))
103 user.create(username="fred", roles='User',
104 password=password.Password('sekrit'), address='fred@example.com')
105 status.create(name="unread")
106 status.create(name="in-progress")
107 status.create(name="testing")
108 status.create(name="resolved")
109 priority.create(name="feature", order="2")
110 priority.create(name="wish", order="3")
111 priority.create(name="bug", order="1")
112 db.commit()
114 class MyTestCase(unittest.TestCase):
115 def tearDown(self):
116 if hasattr(self, 'db'):
117 self.db.close()
118 if os.path.exists(config.DATABASE):
119 shutil.rmtree(config.DATABASE)
121 if os.environ.has_key('LOGGING_LEVEL'):
122 from roundup import rlog
123 config.logging = rlog.BasicLogging()
124 config.logging.setLevel(os.environ['LOGGING_LEVEL'])
125 config.logging.getLogger('hyperdb').setFormat('%(message)s')
127 class DBTest(MyTestCase):
128 def setUp(self):
129 # remove previous test, ignore errors
130 if os.path.exists(config.DATABASE):
131 shutil.rmtree(config.DATABASE)
132 os.makedirs(config.DATABASE + '/files')
133 self.db = self.module.Database(config, 'admin')
134 setupSchema(self.db, 1, self.module)
136 def testRefresh(self):
137 self.db.refresh_database()
139 #
140 # automatic properties (well, the two easy ones anyway)
141 #
142 def testCreatorProperty(self):
143 i = self.db.issue
144 id1 = i.create(title='spam')
145 self.db.commit()
146 self.db.close()
147 self.db = self.module.Database(config, 'fred')
148 setupSchema(self.db, 0, self.module)
149 i = self.db.issue
150 id2 = i.create(title='spam')
151 self.assertNotEqual(id1, id2)
152 self.assertNotEqual(i.get(id1, 'creator'), i.get(id2, 'creator'))
154 def testActorProperty(self):
155 i = self.db.issue
156 id1 = i.create(title='spam')
157 self.db.commit()
158 self.db.close()
159 self.db = self.module.Database(config, 'fred')
160 setupSchema(self.db, 0, self.module)
161 i = self.db.issue
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=sets.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=sets.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(sets.Set(self.db.status.getnodeids()),
491 sets.Set(nodeids))
492 self.assertEqual(sets.Set(self.db.status.getnodeids(retired=True)),
493 sets.Set(['1']))
494 self.assertEqual(sets.Set(self.db.status.getnodeids(retired=False)),
495 sets.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 self.assertEquals(self.db.indexer.search(['world'], self.db.issue), {})
854 self.assertEquals(self.db.indexer.search(['frooz'], self.db.issue),
855 {i2: {}})
856 self.assertEquals(self.db.indexer.search(['flebble'], self.db.issue),
857 {i1: {}, i2: {}})
859 # test AND'ing of search terms
860 self.assertEquals(self.db.indexer.search(['frooz', 'flebble'],
861 self.db.issue), {i2: {}})
863 # unindexed stopword
864 self.assertEquals(self.db.indexer.search(['the'], self.db.issue), {})
866 def testIndexerSearchingLink(self):
867 m1 = self.db.msg.create(content="one two")
868 i1 = self.db.issue.create(messages=[m1])
869 m2 = self.db.msg.create(content="two three")
870 i2 = self.db.issue.create(feedback=m2)
871 self.db.commit()
872 self.assertEquals(self.db.indexer.search(['two'], self.db.issue),
873 {i1: {'messages': [m1]}, i2: {'feedback': [m2]}})
875 def testIndexerSearchMulti(self):
876 m1 = self.db.msg.create(content="one two")
877 m2 = self.db.msg.create(content="two three")
878 i1 = self.db.issue.create(messages=[m1])
879 i2 = self.db.issue.create(spam=[m2])
880 self.db.commit()
881 self.assertEquals(self.db.indexer.search([], self.db.issue), {})
882 self.assertEquals(self.db.indexer.search(['one'], self.db.issue),
883 {i1: {'messages': [m1]}})
884 self.assertEquals(self.db.indexer.search(['two'], self.db.issue),
885 {i1: {'messages': [m1]}, i2: {'spam': [m2]}})
886 self.assertEquals(self.db.indexer.search(['three'], self.db.issue),
887 {i2: {'spam': [m2]}})
889 def testReindexingChange(self):
890 search = self.db.indexer.search
891 issue = self.db.issue
892 i1 = issue.create(title="flebble plop")
893 i2 = issue.create(title="flebble frooz")
894 self.db.commit()
895 self.assertEquals(search(['plop'], issue), {i1: {}})
896 self.assertEquals(search(['flebble'], issue), {i1: {}, i2: {}})
898 # change i1's title
899 issue.set(i1, title="plop")
900 self.db.commit()
901 self.assertEquals(search(['plop'], issue), {i1: {}})
902 self.assertEquals(search(['flebble'], issue), {i2: {}})
904 def testReindexingClear(self):
905 search = self.db.indexer.search
906 issue = self.db.issue
907 i1 = issue.create(title="flebble plop")
908 i2 = issue.create(title="flebble frooz")
909 self.db.commit()
910 self.assertEquals(search(['plop'], issue), {i1: {}})
911 self.assertEquals(search(['flebble'], issue), {i1: {}, i2: {}})
913 # unset i1's title
914 issue.set(i1, title="")
915 self.db.commit()
916 self.assertEquals(search(['plop'], issue), {})
917 self.assertEquals(search(['flebble'], issue), {i2: {}})
919 def testFileClassReindexing(self):
920 f1 = self.db.file.create(content='hello')
921 f2 = self.db.file.create(content='hello, world')
922 i1 = self.db.issue.create(files=[f1, f2])
923 self.db.commit()
924 d = self.db.indexer.search(['hello'], self.db.issue)
925 self.assert_(d.has_key(i1))
926 d[i1]['files'].sort()
927 self.assertEquals(d, {i1: {'files': [f1, f2]}})
928 self.assertEquals(self.db.indexer.search(['world'], self.db.issue),
929 {i1: {'files': [f2]}})
930 self.db.file.set(f1, content="world")
931 self.db.commit()
932 d = self.db.indexer.search(['world'], self.db.issue)
933 d[i1]['files'].sort()
934 self.assertEquals(d, {i1: {'files': [f1, f2]}})
935 self.assertEquals(self.db.indexer.search(['hello'], self.db.issue),
936 {i1: {'files': [f2]}})
938 def testFileClassIndexingNoNoNo(self):
939 f1 = self.db.file.create(content='hello')
940 self.db.commit()
941 self.assertEquals(self.db.indexer.search(['hello'], self.db.file),
942 {'1': {}})
944 f1 = self.db.file_nidx.create(content='hello')
945 self.db.commit()
946 self.assertEquals(self.db.indexer.search(['hello'], self.db.file_nidx),
947 {})
949 def testForcedReindexing(self):
950 self.db.issue.create(title="flebble frooz")
951 self.db.commit()
952 self.assertEquals(self.db.indexer.search(['flebble'], self.db.issue),
953 {'1': {}})
954 self.db.indexer.quiet = 1
955 self.db.indexer.force_reindex()
956 self.db.post_init()
957 self.db.indexer.quiet = 9
958 self.assertEquals(self.db.indexer.search(['flebble'], self.db.issue),
959 {'1': {}})
961 def testIndexingOnImport(self):
962 # import a message
963 msgcontent = 'Glrk'
964 msgid = self.db.msg.import_list(['content', 'files', 'recipients'],
965 [repr(msgcontent), '[]', '[]'])
966 msg_filename = self.db.filename(self.db.msg.classname, msgid,
967 create=1)
968 support.ensureParentsExist(msg_filename)
969 msg_file = open(msg_filename, 'w')
970 msg_file.write(msgcontent)
971 msg_file.close()
973 # import a file
974 filecontent = 'Brrk'
975 fileid = self.db.file.import_list(['content'], [repr(filecontent)])
976 file_filename = self.db.filename(self.db.file.classname, fileid,
977 create=1)
978 support.ensureParentsExist(file_filename)
979 file_file = open(file_filename, 'w')
980 file_file.write(filecontent)
981 file_file.close()
983 # import an issue
984 title = 'Bzzt'
985 nodeid = self.db.issue.import_list(['title', 'messages', 'files',
986 'spam', 'nosy', 'superseder'], [repr(title), repr([msgid]),
987 repr([fileid]), '[]', '[]', '[]'])
988 self.db.commit()
990 # Content of title attribute is indexed
991 self.assertEquals(self.db.indexer.search([title], self.db.issue),
992 {str(nodeid):{}})
993 # Content of message is indexed
994 self.assertEquals(self.db.indexer.search([msgcontent], self.db.issue),
995 {str(nodeid):{'messages':[str(msgid)]}})
996 # Content of file is indexed
997 self.assertEquals(self.db.indexer.search([filecontent], self.db.issue),
998 {str(nodeid):{'files':[str(fileid)]}})
1002 #
1003 # searching tests follow
1004 #
1005 def testFindIncorrectProperty(self):
1006 self.assertRaises(TypeError, self.db.issue.find, title='fubar')
1008 def _find_test_setup(self):
1009 self.db.file.create(content='')
1010 self.db.file.create(content='')
1011 self.db.user.create(username='')
1012 one = self.db.issue.create(status="1", nosy=['1'])
1013 two = self.db.issue.create(status="2", nosy=['2'], files=['1'],
1014 assignedto='2')
1015 three = self.db.issue.create(status="1", nosy=['1','2'])
1016 four = self.db.issue.create(status="3", assignedto='1',
1017 files=['1','2'])
1018 return one, two, three, four
1020 def testFindLink(self):
1021 one, two, three, four = self._find_test_setup()
1022 got = self.db.issue.find(status='1')
1023 got.sort()
1024 self.assertEqual(got, [one, three])
1025 got = self.db.issue.find(status={'1':1})
1026 got.sort()
1027 self.assertEqual(got, [one, three])
1029 def testFindLinkFail(self):
1030 self._find_test_setup()
1031 self.assertEqual(self.db.issue.find(status='4'), [])
1032 self.assertEqual(self.db.issue.find(status={'4':1}), [])
1034 def testFindLinkUnset(self):
1035 one, two, three, four = self._find_test_setup()
1036 got = self.db.issue.find(assignedto=None)
1037 got.sort()
1038 self.assertEqual(got, [one, three])
1039 got = self.db.issue.find(assignedto={None:1})
1040 got.sort()
1041 self.assertEqual(got, [one, three])
1043 def testFindMultipleLink(self):
1044 one, two, three, four = self._find_test_setup()
1045 l = self.db.issue.find(status={'1':1, '3':1})
1046 l.sort()
1047 self.assertEqual(l, [one, three, four])
1048 l = self.db.issue.find(assignedto={None:1, '1':1})
1049 l.sort()
1050 self.assertEqual(l, [one, three, four])
1052 def testFindMultilink(self):
1053 one, two, three, four = self._find_test_setup()
1054 got = self.db.issue.find(nosy='2')
1055 got.sort()
1056 self.assertEqual(got, [two, three])
1057 got = self.db.issue.find(nosy={'2':1})
1058 got.sort()
1059 self.assertEqual(got, [two, three])
1060 got = self.db.issue.find(nosy={'2':1}, files={})
1061 got.sort()
1062 self.assertEqual(got, [two, three])
1064 def testFindMultiMultilink(self):
1065 one, two, three, four = self._find_test_setup()
1066 got = self.db.issue.find(nosy='2', files='1')
1067 got.sort()
1068 self.assertEqual(got, [two, three, four])
1069 got = self.db.issue.find(nosy={'2':1}, files={'1':1})
1070 got.sort()
1071 self.assertEqual(got, [two, three, four])
1073 def testFindMultilinkFail(self):
1074 self._find_test_setup()
1075 self.assertEqual(self.db.issue.find(nosy='3'), [])
1076 self.assertEqual(self.db.issue.find(nosy={'3':1}), [])
1078 def testFindMultilinkUnset(self):
1079 self._find_test_setup()
1080 self.assertEqual(self.db.issue.find(nosy={}), [])
1082 def testFindLinkAndMultilink(self):
1083 one, two, three, four = self._find_test_setup()
1084 got = self.db.issue.find(status='1', nosy='2')
1085 got.sort()
1086 self.assertEqual(got, [one, two, three])
1087 got = self.db.issue.find(status={'1':1}, nosy={'2':1})
1088 got.sort()
1089 self.assertEqual(got, [one, two, three])
1091 def testFindRetired(self):
1092 one, two, three, four = self._find_test_setup()
1093 self.assertEqual(len(self.db.issue.find(status='1')), 2)
1094 self.db.issue.retire(one)
1095 self.assertEqual(len(self.db.issue.find(status='1')), 1)
1097 def testStringFind(self):
1098 self.assertRaises(TypeError, self.db.issue.stringFind, status='1')
1100 ids = []
1101 ids.append(self.db.issue.create(title="spam"))
1102 self.db.issue.create(title="not spam")
1103 ids.append(self.db.issue.create(title="spam"))
1104 ids.sort()
1105 got = self.db.issue.stringFind(title='spam')
1106 got.sort()
1107 self.assertEqual(got, ids)
1108 self.assertEqual(self.db.issue.stringFind(title='fubar'), [])
1110 # test retiring a node
1111 self.db.issue.retire(ids[0])
1112 self.assertEqual(len(self.db.issue.stringFind(title='spam')), 1)
1114 def filteringSetup(self):
1115 for user in (
1116 {'username': 'bleep', 'age': 1},
1117 {'username': 'blop', 'age': 1.5},
1118 {'username': 'blorp', 'age': 2}):
1119 self.db.user.create(**user)
1120 iss = self.db.issue
1121 file_content = ''.join([chr(i) for i in range(255)])
1122 f = self.db.file.create(content=file_content)
1123 for issue in (
1124 {'title': 'issue one', 'status': '2', 'assignedto': '1',
1125 'foo': date.Interval('1:10'), 'priority': '3',
1126 'deadline': date.Date('2003-02-16.22:50')},
1127 {'title': 'issue two', 'status': '1', 'assignedto': '2',
1128 'foo': date.Interval('1d'), 'priority': '3',
1129 'deadline': date.Date('2003-01-01.00:00')},
1130 {'title': 'issue three', 'status': '1', 'priority': '2',
1131 'nosy': ['1','2'], 'deadline': date.Date('2003-02-18')},
1132 {'title': 'non four', 'status': '3',
1133 'foo': date.Interval('0:10'), 'priority': '2',
1134 'nosy': ['1','2','3'], 'deadline': date.Date('2004-03-08'),
1135 'files': [f]}):
1136 self.db.issue.create(**issue)
1137 self.db.commit()
1138 return self.assertEqual, self.db.issue.filter
1140 def testFilteringID(self):
1141 ae, filt = self.filteringSetup()
1142 ae(filt(None, {'id': '1'}, ('+','id'), (None,None)), ['1'])
1143 ae(filt(None, {'id': '2'}, ('+','id'), (None,None)), ['2'])
1144 ae(filt(None, {'id': '100'}, ('+','id'), (None,None)), [])
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'])
1154 def testFilteringString(self):
1155 ae, filt = self.filteringSetup()
1156 ae(filt(None, {'title': ['one']}, ('+','id'), (None,None)), ['1'])
1157 ae(filt(None, {'title': ['issue one']}, ('+','id'), (None,None)),
1158 ['1'])
1159 ae(filt(None, {'title': ['issue', 'one']}, ('+','id'), (None,None)),
1160 ['1'])
1161 ae(filt(None, {'title': ['issue']}, ('+','id'), (None,None)),
1162 ['1','2','3'])
1163 ae(filt(None, {'title': ['one', 'two']}, ('+','id'), (None,None)),
1164 [])
1166 def testFilteringLink(self):
1167 ae, filt = self.filteringSetup()
1168 ae(filt(None, {'status': '1'}, ('+','id'), (None,None)), ['2','3'])
1169 ae(filt(None, {'assignedto': '-1'}, ('+','id'), (None,None)), ['3','4'])
1170 ae(filt(None, {'assignedto': None}, ('+','id'), (None,None)), ['3','4'])
1171 ae(filt(None, {'assignedto': [None]}, ('+','id'), (None,None)),
1172 ['3','4'])
1173 ae(filt(None, {'assignedto': ['-1', None]}, ('+','id'), (None,None)),
1174 ['3','4'])
1175 ae(filt(None, {'assignedto': ['1', None]}, ('+','id'), (None,None)),
1176 ['1', '3','4'])
1178 def testFilteringMultilinkAndGroup(self):
1179 """testFilteringMultilinkAndGroup:
1180 See roundup Bug 1541128: apparently grouping by something and
1181 searching a Multilink failed with MySQL 5.0
1182 """
1183 ae, filt = self.filteringSetup()
1184 ae(filt(None, {'files': '1'}, ('-','activity'), ('+','status')), ['4'])
1186 def testFilteringRetired(self):
1187 ae, filt = self.filteringSetup()
1188 self.db.issue.retire('2')
1189 ae(filt(None, {'status': '1'}, ('+','id'), (None,None)), ['3'])
1191 def testFilteringMultilink(self):
1192 ae, filt = self.filteringSetup()
1193 ae(filt(None, {'nosy': '3'}, ('+','id'), (None,None)), ['4'])
1194 ae(filt(None, {'nosy': '-1'}, ('+','id'), (None,None)), ['1', '2'])
1195 ae(filt(None, {'nosy': ['1','2']}, ('+', 'status'),
1196 ('-', 'deadline')), ['4', '3'])
1198 def testFilteringMany(self):
1199 ae, filt = self.filteringSetup()
1200 ae(filt(None, {'nosy': '2', 'status': '1'}, ('+','id'), (None,None)),
1201 ['3'])
1203 def testFilteringRangeBasic(self):
1204 ae, filt = self.filteringSetup()
1205 ae(filt(None, {'deadline': 'from 2003-02-10 to 2003-02-23'}), ['1','3'])
1206 ae(filt(None, {'deadline': '2003-02-10; 2003-02-23'}), ['1','3'])
1207 ae(filt(None, {'deadline': '; 2003-02-16'}), ['2'])
1209 def testFilteringRangeTwoSyntaxes(self):
1210 ae, filt = self.filteringSetup()
1211 ae(filt(None, {'deadline': 'from 2003-02-16'}), ['1', '3', '4'])
1212 ae(filt(None, {'deadline': '2003-02-16;'}), ['1', '3', '4'])
1214 def testFilteringRangeYearMonthDay(self):
1215 ae, filt = self.filteringSetup()
1216 ae(filt(None, {'deadline': '2002'}), [])
1217 ae(filt(None, {'deadline': '2003'}), ['1', '2', '3'])
1218 ae(filt(None, {'deadline': '2004'}), ['4'])
1219 ae(filt(None, {'deadline': '2003-02-16'}), ['1'])
1220 ae(filt(None, {'deadline': '2003-02-17'}), [])
1222 def testFilteringRangeMonths(self):
1223 ae, filt = self.filteringSetup()
1224 for month in range(1, 13):
1225 for n in range(1, month+1):
1226 i = self.db.issue.create(title='%d.%d'%(month, n),
1227 deadline=date.Date('2001-%02d-%02d.00:00'%(month, n)))
1228 self.db.commit()
1230 for month in range(1, 13):
1231 r = filt(None, dict(deadline='2001-%02d'%month))
1232 assert len(r) == month, 'month %d != length %d'%(month, len(r))
1234 def testFilteringRangeInterval(self):
1235 ae, filt = self.filteringSetup()
1236 ae(filt(None, {'foo': 'from 0:50 to 2:00'}), ['1'])
1237 ae(filt(None, {'foo': 'from 0:50 to 1d 2:00'}), ['1', '2'])
1238 ae(filt(None, {'foo': 'from 5:50'}), ['2'])
1239 ae(filt(None, {'foo': 'to 0:05'}), [])
1241 def testFilteringRangeGeekInterval(self):
1242 ae, filt = self.filteringSetup()
1243 for issue in (
1244 { 'deadline': date.Date('. -2d')},
1245 { 'deadline': date.Date('. -1d')},
1246 { 'deadline': date.Date('. -8d')},
1247 ):
1248 self.db.issue.create(**issue)
1249 ae(filt(None, {'deadline': '-2d;'}), ['5', '6'])
1250 ae(filt(None, {'deadline': '-1d;'}), ['6'])
1251 ae(filt(None, {'deadline': '-1w;'}), ['5', '6'])
1253 def testFilteringIntervalSort(self):
1254 # 1: '1:10'
1255 # 2: '1d'
1256 # 3: None
1257 # 4: '0:10'
1258 ae, filt = self.filteringSetup()
1259 # ascending should sort None, 1:10, 1d
1260 ae(filt(None, {}, ('+','foo'), (None,None)), ['3', '4', '1', '2'])
1261 # descending should sort 1d, 1:10, None
1262 ae(filt(None, {}, ('-','foo'), (None,None)), ['2', '1', '4', '3'])
1264 def testFilteringStringSort(self):
1265 # 1: 'issue one'
1266 # 2: 'issue two'
1267 # 3: 'issue three'
1268 # 4: 'non four'
1269 ae, filt = self.filteringSetup()
1270 ae(filt(None, {}, ('+','title')), ['1', '3', '2', '4'])
1271 ae(filt(None, {}, ('-','title')), ['4', '2', '3', '1'])
1272 # Test string case: For now allow both, w/wo case matching.
1273 # 1: 'issue one'
1274 # 2: 'issue two'
1275 # 3: 'Issue three'
1276 # 4: 'non four'
1277 self.db.issue.set('3', title='Issue three')
1278 ae(filt(None, {}, ('+','title')), ['1', '3', '2', '4'])
1279 ae(filt(None, {}, ('-','title')), ['4', '2', '3', '1'])
1280 # Obscure bug in anydbm backend trying to convert to number
1281 # 1: '1st issue'
1282 # 2: '2'
1283 # 3: 'Issue three'
1284 # 4: 'non four'
1285 self.db.issue.set('1', title='1st issue')
1286 self.db.issue.set('2', title='2')
1287 ae(filt(None, {}, ('+','title')), ['1', '2', '3', '4'])
1288 ae(filt(None, {}, ('-','title')), ['4', '3', '2', '1'])
1290 def testFilteringMultilinkSort(self):
1291 # 1: [] Reverse: 1: []
1292 # 2: [] 2: []
1293 # 3: ['admin','fred'] 3: ['fred','admin']
1294 # 4: ['admin','bleep','fred'] 4: ['fred','bleep','admin']
1295 # Note the sort order for the multilink doen't change when
1296 # reversing the sort direction due to the re-sorting of the
1297 # multilink!
1298 ae, filt = self.filteringSetup()
1299 ae(filt(None, {}, ('+','nosy'), (None,None)), ['1', '2', '4', '3'])
1300 ae(filt(None, {}, ('-','nosy'), (None,None)), ['4', '3', '1', '2'])
1302 def testFilteringMultilinkSortGroup(self):
1303 # 1: status: 2 "in-progress" nosy: []
1304 # 2: status: 1 "unread" nosy: []
1305 # 3: status: 1 "unread" nosy: ['admin','fred']
1306 # 4: status: 3 "testing" nosy: ['admin','bleep','fred']
1307 ae, filt = self.filteringSetup()
1308 ae(filt(None, {}, ('+','nosy'), ('+','status')), ['1', '4', '2', '3'])
1309 ae(filt(None, {}, ('-','nosy'), ('+','status')), ['1', '4', '3', '2'])
1310 ae(filt(None, {}, ('+','nosy'), ('-','status')), ['2', '3', '4', '1'])
1311 ae(filt(None, {}, ('-','nosy'), ('-','status')), ['3', '2', '4', '1'])
1312 ae(filt(None, {}, ('+','status'), ('+','nosy')), ['1', '2', '4', '3'])
1313 ae(filt(None, {}, ('-','status'), ('+','nosy')), ['2', '1', '4', '3'])
1314 ae(filt(None, {}, ('+','status'), ('-','nosy')), ['4', '3', '1', '2'])
1315 ae(filt(None, {}, ('-','status'), ('-','nosy')), ['4', '3', '2', '1'])
1317 def testFilteringLinkSortGroup(self):
1318 # 1: status: 2 -> 'i', priority: 3 -> 1
1319 # 2: status: 1 -> 'u', priority: 3 -> 1
1320 # 3: status: 1 -> 'u', priority: 2 -> 3
1321 # 4: status: 3 -> 't', priority: 2 -> 3
1322 ae, filt = self.filteringSetup()
1323 ae(filt(None, {}, ('+','status'), ('+','priority')),
1324 ['1', '2', '4', '3'])
1325 ae(filt(None, {'priority':'2'}, ('+','status'), ('+','priority')),
1326 ['4', '3'])
1327 ae(filt(None, {'priority.order':'3'}, ('+','status'), ('+','priority')),
1328 ['4', '3'])
1329 ae(filt(None, {'priority':['2','3']}, ('+','priority'), ('+','status')),
1330 ['1', '4', '2', '3'])
1331 ae(filt(None, {}, ('+','priority'), ('+','status')),
1332 ['1', '4', '2', '3'])
1334 def testFilteringDateSort(self):
1335 # '1': '2003-02-16.22:50'
1336 # '2': '2003-01-01.00:00'
1337 # '3': '2003-02-18'
1338 # '4': '2004-03-08'
1339 ae, filt = self.filteringSetup()
1340 # ascending
1341 ae(filt(None, {}, ('+','deadline'), (None,None)), ['2', '1', '3', '4'])
1342 # descending
1343 ae(filt(None, {}, ('-','deadline'), (None,None)), ['4', '3', '1', '2'])
1345 def testFilteringDateSortPriorityGroup(self):
1346 # '1': '2003-02-16.22:50' 1 => 2
1347 # '2': '2003-01-01.00:00' 3 => 1
1348 # '3': '2003-02-18' 2 => 3
1349 # '4': '2004-03-08' 1 => 2
1350 ae, filt = self.filteringSetup()
1352 # ascending
1353 ae(filt(None, {}, ('+','deadline'), ('+','priority')),
1354 ['2', '1', '3', '4'])
1355 ae(filt(None, {}, ('-','deadline'), ('+','priority')),
1356 ['1', '2', '4', '3'])
1357 # descending
1358 ae(filt(None, {}, ('+','deadline'), ('-','priority')),
1359 ['3', '4', '2', '1'])
1360 ae(filt(None, {}, ('-','deadline'), ('-','priority')),
1361 ['4', '3', '1', '2'])
1363 def filteringSetupTransitiveSearch(self):
1364 u_m = {}
1365 k = 30
1366 for user in (
1367 {'username': 'ceo', 'age': 129},
1368 {'username': 'grouplead1', 'age': 29, 'supervisor': '3'},
1369 {'username': 'grouplead2', 'age': 29, 'supervisor': '3'},
1370 {'username': 'worker1', 'age': 25, 'supervisor' : '4'},
1371 {'username': 'worker2', 'age': 24, 'supervisor' : '4'},
1372 {'username': 'worker3', 'age': 23, 'supervisor' : '5'},
1373 {'username': 'worker4', 'age': 22, 'supervisor' : '5'},
1374 {'username': 'worker5', 'age': 21, 'supervisor' : '5'}):
1375 u = self.db.user.create(**user)
1376 u_m [u] = self.db.msg.create(author = u, content = ' '
1377 , date = date.Date ('2006-01-%s' % k))
1378 k -= 1
1379 iss = self.db.issue
1380 for issue in (
1381 {'title': 'ts1', 'status': '2', 'assignedto': '6',
1382 'priority': '3', 'messages' : [u_m ['6']], 'nosy' : ['4']},
1383 {'title': 'ts2', 'status': '1', 'assignedto': '6',
1384 'priority': '3', 'messages' : [u_m ['6']], 'nosy' : ['5']},
1385 {'title': 'ts4', 'status': '2', 'assignedto': '7',
1386 'priority': '3', 'messages' : [u_m ['7']]},
1387 {'title': 'ts5', 'status': '1', 'assignedto': '8',
1388 'priority': '3', 'messages' : [u_m ['8']]},
1389 {'title': 'ts6', 'status': '2', 'assignedto': '9',
1390 'priority': '3', 'messages' : [u_m ['9']]},
1391 {'title': 'ts7', 'status': '1', 'assignedto': '10',
1392 'priority': '3', 'messages' : [u_m ['10']]},
1393 {'title': 'ts8', 'status': '2', 'assignedto': '10',
1394 'priority': '3', 'messages' : [u_m ['10']]},
1395 {'title': 'ts9', 'status': '1', 'assignedto': '10',
1396 'priority': '3', 'messages' : [u_m ['10'], u_m ['9']]}):
1397 self.db.issue.create(**issue)
1398 return self.assertEqual, self.db.issue.filter
1400 def testFilteringTransitiveLinkUser(self):
1401 ae, filt = self.filteringSetupTransitiveSearch()
1402 ufilt = self.db.user.filter
1403 ae(ufilt(None, {'supervisor.username': 'ceo'}, ('+','username')),
1404 ['4', '5'])
1405 ae(ufilt(None, {'supervisor.supervisor.username': 'ceo'},
1406 ('+','username')), ['6', '7', '8', '9', '10'])
1407 ae(ufilt(None, {'supervisor.supervisor': '3'}, ('+','username')),
1408 ['6', '7', '8', '9', '10'])
1409 ae(ufilt(None, {'supervisor.supervisor.id': '3'}, ('+','username')),
1410 ['6', '7', '8', '9', '10'])
1411 ae(ufilt(None, {'supervisor.username': 'grouplead1'}, ('+','username')),
1412 ['6', '7'])
1413 ae(ufilt(None, {'supervisor.username': 'grouplead2'}, ('+','username')),
1414 ['8', '9', '10'])
1415 ae(ufilt(None, {'supervisor.username': 'grouplead2',
1416 'supervisor.supervisor.username': 'ceo'}, ('+','username')),
1417 ['8', '9', '10'])
1418 ae(ufilt(None, {'supervisor.supervisor': '3', 'supervisor': '4'},
1419 ('+','username')), ['6', '7'])
1421 def testFilteringTransitiveLinkSort(self):
1422 ae, filt = self.filteringSetupTransitiveSearch()
1423 ufilt = self.db.user.filter
1424 # Need to make ceo his own (and first two users') supervisor,
1425 # otherwise we will depend on sorting order of NULL values.
1426 # Leave that to a separate test.
1427 self.db.user.set('1', supervisor = '3')
1428 self.db.user.set('2', supervisor = '3')
1429 self.db.user.set('3', supervisor = '3')
1430 ae(ufilt(None, {'supervisor':'3'}, []), ['1', '2', '3', '4', '5'])
1431 ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1432 ('+','supervisor.supervisor'), ('+','supervisor'),
1433 ('+','username')]),
1434 ['1', '3', '2', '4', '5', '6', '7', '8', '9', '10'])
1435 ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1436 ('-','supervisor.supervisor'), ('-','supervisor'),
1437 ('+','username')]),
1438 ['8', '9', '10', '6', '7', '1', '3', '2', '4', '5'])
1439 ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1440 ('+','assignedto.supervisor.supervisor'),
1441 ('+','assignedto.supervisor'), ('+','assignedto')]),
1442 ['1', '2', '3', '4', '5', '6', '7', '8'])
1443 ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1444 ('+','assignedto.supervisor.supervisor'),
1445 ('-','assignedto.supervisor'), ('+','assignedto')]),
1446 ['4', '5', '6', '7', '8', '1', '2', '3'])
1447 ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1448 ('+','assignedto.supervisor.supervisor'),
1449 ('+','assignedto.supervisor'), ('+','assignedto'),
1450 ('-','status')]),
1451 ['2', '1', '3', '4', '5', '6', '8', '7'])
1452 ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1453 ('+','assignedto.supervisor.supervisor'),
1454 ('+','assignedto.supervisor'), ('+','assignedto'),
1455 ('+','status')]),
1456 ['1', '2', '3', '4', '5', '7', '6', '8'])
1457 ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1458 ('+','assignedto.supervisor.supervisor'),
1459 ('-','assignedto.supervisor'), ('+','assignedto'), ('+','status')]),
1460 ['4', '5', '7', '6', '8', '1', '2', '3'])
1461 ae(filt(None, {'assignedto':['6','7','8','9','10']},
1462 [('+','assignedto.supervisor.supervisor.supervisor'),
1463 ('+','assignedto.supervisor.supervisor'),
1464 ('-','assignedto.supervisor'), ('+','assignedto'), ('+','status')]),
1465 ['4', '5', '7', '6', '8', '1', '2', '3'])
1466 ae(filt(None, {'assignedto':['6','7','8','9']},
1467 [('+','assignedto.supervisor.supervisor.supervisor'),
1468 ('+','assignedto.supervisor.supervisor'),
1469 ('-','assignedto.supervisor'), ('+','assignedto'), ('+','status')]),
1470 ['4', '5', '1', '2', '3'])
1472 def testFilteringTransitiveLinkSortNull(self):
1473 """Check sorting of NULL values"""
1474 ae, filt = self.filteringSetupTransitiveSearch()
1475 ufilt = self.db.user.filter
1476 ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1477 ('+','supervisor.supervisor'), ('+','supervisor'),
1478 ('+','username')]),
1479 ['1', '3', '2', '4', '5', '6', '7', '8', '9', '10'])
1480 ae(ufilt(None, {}, [('+','supervisor.supervisor.supervisor'),
1481 ('-','supervisor.supervisor'), ('-','supervisor'),
1482 ('+','username')]),
1483 ['8', '9', '10', '6', '7', '4', '5', '1', '3', '2'])
1484 ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1485 ('+','assignedto.supervisor.supervisor'),
1486 ('+','assignedto.supervisor'), ('+','assignedto')]),
1487 ['1', '2', '3', '4', '5', '6', '7', '8'])
1488 ae(filt(None, {}, [('+','assignedto.supervisor.supervisor.supervisor'),
1489 ('+','assignedto.supervisor.supervisor'),
1490 ('-','assignedto.supervisor'), ('+','assignedto')]),
1491 ['4', '5', '6', '7', '8', '1', '2', '3'])
1493 def testFilteringTransitiveLinkIssue(self):
1494 ae, filt = self.filteringSetupTransitiveSearch()
1495 ae(filt(None, {'assignedto.supervisor.username': 'grouplead1'},
1496 ('+','id')), ['1', '2', '3'])
1497 ae(filt(None, {'assignedto.supervisor.username': 'grouplead2'},
1498 ('+','id')), ['4', '5', '6', '7', '8'])
1499 ae(filt(None, {'assignedto.supervisor.username': 'grouplead2',
1500 'status': '1'}, ('+','id')), ['4', '6', '8'])
1501 ae(filt(None, {'assignedto.supervisor.username': 'grouplead2',
1502 'status': '2'}, ('+','id')), ['5', '7'])
1503 ae(filt(None, {'assignedto.supervisor.username': ['grouplead2'],
1504 'status': '2'}, ('+','id')), ['5', '7'])
1505 ae(filt(None, {'assignedto.supervisor': ['4', '5'], 'status': '2'},
1506 ('+','id')), ['1', '3', '5', '7'])
1508 def testFilteringTransitiveMultilink(self):
1509 ae, filt = self.filteringSetupTransitiveSearch()
1510 ae(filt(None, {'messages.author.username': 'grouplead1'},
1511 ('+','id')), [])
1512 ae(filt(None, {'messages.author': '6'},
1513 ('+','id')), ['1', '2'])
1514 ae(filt(None, {'messages.author.id': '6'},
1515 ('+','id')), ['1', '2'])
1516 ae(filt(None, {'messages.author.username': 'worker1'},
1517 ('+','id')), ['1', '2'])
1518 ae(filt(None, {'messages.author': '10'},
1519 ('+','id')), ['6', '7', '8'])
1520 ae(filt(None, {'messages.author': '9'},
1521 ('+','id')), ['5', '8'])
1522 ae(filt(None, {'messages.author': ['9', '10']},
1523 ('+','id')), ['5', '6', '7', '8'])
1524 ae(filt(None, {'messages.author': ['8', '9']},
1525 ('+','id')), ['4', '5', '8'])
1526 ae(filt(None, {'messages.author': ['8', '9'], 'status' : '1'},
1527 ('+','id')), ['4', '8'])
1528 ae(filt(None, {'messages.author': ['8', '9'], 'status' : '2'},
1529 ('+','id')), ['5'])
1530 ae(filt(None, {'messages.author': ['8', '9', '10'],
1531 'messages.date': '2006-01-22.21:00;2006-01-23'}, ('+','id')),
1532 ['6', '7', '8'])
1533 ae(filt(None, {'nosy.supervisor.username': 'ceo'},
1534 ('+','id')), ['1', '2'])
1535 ae(filt(None, {'messages.author': ['6', '9']},
1536 ('+','id')), ['1', '2', '5', '8'])
1537 ae(filt(None, {'messages': ['5', '7']},
1538 ('+','id')), ['3', '5', '8'])
1539 ae(filt(None, {'messages.author': ['6', '9'], 'messages': ['5', '7']},
1540 ('+','id')), ['5', '8'])
1542 def testFilteringTransitiveMultilinkSort(self):
1543 ae, filt = self.filteringSetupTransitiveSearch()
1544 ae(filt(None, {}, [('+','messages.author')]),
1545 ['1', '2', '3', '4', '5', '8', '6', '7'])
1546 ae(filt(None, {}, [('-','messages.author')]),
1547 ['8', '6', '7', '5', '4', '3', '1', '2'])
1548 ae(filt(None, {}, [('+','messages.date')]),
1549 ['6', '7', '8', '5', '4', '3', '1', '2'])
1550 ae(filt(None, {}, [('-','messages.date')]),
1551 ['1', '2', '3', '4', '8', '5', '6', '7'])
1552 ae(filt(None, {}, [('+','messages.author'),('+','messages.date')]),
1553 ['1', '2', '3', '4', '5', '8', '6', '7'])
1554 ae(filt(None, {}, [('-','messages.author'),('+','messages.date')]),
1555 ['8', '6', '7', '5', '4', '3', '1', '2'])
1556 ae(filt(None, {}, [('+','messages.author'),('-','messages.date')]),
1557 ['1', '2', '3', '4', '5', '8', '6', '7'])
1558 ae(filt(None, {}, [('-','messages.author'),('-','messages.date')]),
1559 ['8', '6', '7', '5', '4', '3', '1', '2'])
1560 ae(filt(None, {}, [('+','messages.author'),('+','assignedto')]),
1561 ['1', '2', '3', '4', '5', '8', '6', '7'])
1562 ae(filt(None, {}, [('+','messages.author'),
1563 ('-','assignedto.supervisor'),('-','assignedto')]),
1564 ['1', '2', '3', '4', '5', '8', '6', '7'])
1565 ae(filt(None, {},
1566 [('+','messages.author.supervisor.supervisor.supervisor'),
1567 ('+','messages.author.supervisor.supervisor'),
1568 ('+','messages.author.supervisor'), ('+','messages.author')]),
1569 ['1', '2', '3', '4', '5', '6', '7', '8'])
1570 self.db.user.setorderprop('age')
1571 self.db.msg.setorderprop('date')
1572 ae(filt(None, {}, [('+','messages'), ('+','messages.author')]),
1573 ['6', '7', '8', '5', '4', '3', '1', '2'])
1574 ae(filt(None, {}, [('+','messages.author'), ('+','messages')]),
1575 ['6', '7', '8', '5', '4', '3', '1', '2'])
1576 self.db.msg.setorderprop('author')
1577 # Orderprop is a Link/Multilink:
1578 # messages are sorted by orderprop().labelprop(), i.e. by
1579 # author.username, *not* by author.orderprop() (author.age)!
1580 ae(filt(None, {}, [('+','messages')]),
1581 ['1', '2', '3', '4', '5', '8', '6', '7'])
1582 ae(filt(None, {}, [('+','messages.author'), ('+','messages')]),
1583 ['6', '7', '8', '5', '4', '3', '1', '2'])
1584 # The following will sort by
1585 # author.supervisor.username and then by
1586 # author.username
1587 # I've resited the tempation to implement recursive orderprop
1588 # here: There could even be loops if several classes specify a
1589 # Link or Multilink as the orderprop...
1590 # msg: 4: worker1 (id 5) : grouplead1 (id 4) ceo (id 3)
1591 # msg: 5: worker2 (id 7) : grouplead1 (id 4) ceo (id 3)
1592 # msg: 6: worker3 (id 8) : grouplead2 (id 5) ceo (id 3)
1593 # msg: 7: worker4 (id 9) : grouplead2 (id 5) ceo (id 3)
1594 # msg: 8: worker5 (id 10) : grouplead2 (id 5) ceo (id 3)
1595 # issue 1: messages 4 sortkey:[[grouplead1], [worker1], 1]
1596 # issue 2: messages 4 sortkey:[[grouplead1], [worker1], 2]
1597 # issue 3: messages 5 sortkey:[[grouplead1], [worker2], 3]
1598 # issue 4: messages 6 sortkey:[[grouplead2], [worker3], 4]
1599 # issue 5: messages 7 sortkey:[[grouplead2], [worker4], 5]
1600 # issue 6: messages 8 sortkey:[[grouplead2], [worker5], 6]
1601 # issue 7: messages 8 sortkey:[[grouplead2], [worker5], 7]
1602 # issue 8: messages 7,8 sortkey:[[grouplead2, grouplead2], ...]
1603 self.db.user.setorderprop('supervisor')
1604 ae(filt(None, {}, [('+','messages.author'), ('-','messages')]),
1605 ['3', '1', '2', '6', '7', '5', '4', '8'])
1607 def testFilteringSortId(self):
1608 ae, filt = self.filteringSetupTransitiveSearch()
1609 ae(self.db.user.filter(None, {}, ('+','id')),
1610 ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'])
1612 # XXX add sorting tests for other types
1614 def testImportExport(self):
1615 # use the filtering setup to create a bunch of items
1616 ae, filt = self.filteringSetup()
1617 # Get some stuff into the journal for testing import/export of
1618 # journal data:
1619 self.db.user.set('4', password = password.Password('xyzzy'))
1620 self.db.user.set('4', age = 3)
1621 self.db.user.set('4', assignable = True)
1622 self.db.issue.set('1', title = 'i1', status = '3')
1623 self.db.issue.set('1', deadline = date.Date('2007'))
1624 self.db.issue.set('1', foo = date.Interval('1:20'))
1625 p = self.db.priority.create(name = 'some_prio_without_order')
1626 self.db.commit()
1627 self.db.user.set('4', password = password.Password('123xyzzy'))
1628 self.db.user.set('4', assignable = False)
1629 self.db.priority.set(p, order = '4711')
1630 self.db.commit()
1632 self.db.user.retire('3')
1633 self.db.issue.retire('2')
1635 # grab snapshot of the current database
1636 orig = {}
1637 origj = {}
1638 for cn,klass in self.db.classes.items():
1639 cl = orig[cn] = {}
1640 jn = origj[cn] = {}
1641 for id in klass.list():
1642 it = cl[id] = {}
1643 jn[id] = self.db.getjournal(cn, id)
1644 for name in klass.getprops().keys():
1645 it[name] = klass.get(id, name)
1647 os.mkdir('_test_export')
1648 try:
1649 # grab the export
1650 export = {}
1651 journals = {}
1652 for cn,klass in self.db.classes.items():
1653 names = klass.export_propnames()
1654 cl = export[cn] = [names+['is retired']]
1655 for id in klass.getnodeids():
1656 cl.append(klass.export_list(names, id))
1657 if hasattr(klass, 'export_files'):
1658 klass.export_files('_test_export', id)
1659 journals[cn] = klass.export_journals()
1661 # shut down this db and nuke it
1662 self.db.close()
1663 self.nuke_database()
1665 # open a new, empty database
1666 os.makedirs(config.DATABASE + '/files')
1667 self.db = self.module.Database(config, 'admin')
1668 setupSchema(self.db, 0, self.module)
1670 # import
1671 for cn, items in export.items():
1672 klass = self.db.classes[cn]
1673 names = items[0]
1674 maxid = 1
1675 for itemprops in items[1:]:
1676 id = int(klass.import_list(names, itemprops))
1677 if hasattr(klass, 'import_files'):
1678 klass.import_files('_test_export', str(id))
1679 maxid = max(maxid, id)
1680 self.db.setid(cn, str(maxid+1))
1681 klass.import_journals(journals[cn])
1682 # This is needed, otherwise journals won't be there for anydbm
1683 self.db.commit()
1684 finally:
1685 shutil.rmtree('_test_export')
1687 # compare with snapshot of the database
1688 for cn, items in orig.iteritems():
1689 klass = self.db.classes[cn]
1690 propdefs = klass.getprops(1)
1691 # ensure retired items are retired :)
1692 l = items.keys(); l.sort()
1693 m = klass.list(); m.sort()
1694 ae(l, m, '%s id list wrong %r vs. %r'%(cn, l, m))
1695 for id, props in items.items():
1696 for name, value in props.items():
1697 l = klass.get(id, name)
1698 if isinstance(value, type([])):
1699 value.sort()
1700 l.sort()
1701 try:
1702 ae(l, value)
1703 except AssertionError:
1704 if not isinstance(propdefs[name], Date):
1705 raise
1706 # don't get hung up on rounding errors
1707 assert not l.__cmp__(value, int_seconds=1)
1708 for jc, items in origj.iteritems():
1709 for id, oj in items.iteritems():
1710 rj = self.db.getjournal(jc, id)
1711 # Both mysql and postgresql have some minor issues with
1712 # rounded seconds on export/import, so we compare only
1713 # the integer part.
1714 for j in oj:
1715 j[1].second = float(int(j[1].second))
1716 for j in rj:
1717 j[1].second = float(int(j[1].second))
1718 oj.sort()
1719 rj.sort()
1720 ae(oj, rj)
1722 # make sure the retired items are actually imported
1723 ae(self.db.user.get('4', 'username'), 'blop')
1724 ae(self.db.issue.get('2', 'title'), 'issue two')
1726 # make sure id counters are set correctly
1727 maxid = max([int(id) for id in self.db.user.list()])
1728 newid = self.db.user.create(username='testing')
1729 assert newid > maxid
1731 def testAddProperty(self):
1732 self.db.issue.create(title="spam", status='1')
1733 self.db.commit()
1735 self.db.issue.addprop(fixer=Link("user"))
1736 # force any post-init stuff to happen
1737 self.db.post_init()
1738 props = self.db.issue.getprops()
1739 keys = props.keys()
1740 keys.sort()
1741 self.assertEqual(keys, ['activity', 'actor', 'assignedto', 'creation',
1742 'creator', 'deadline', 'feedback', 'files', 'fixer', 'foo', 'id', 'messages',
1743 'nosy', 'priority', 'spam', 'status', 'superseder', 'title'])
1744 self.assertEqual(self.db.issue.get('1', "fixer"), None)
1746 def testRemoveProperty(self):
1747 self.db.issue.create(title="spam", status='1')
1748 self.db.commit()
1750 del self.db.issue.properties['title']
1751 self.db.post_init()
1752 props = self.db.issue.getprops()
1753 keys = props.keys()
1754 keys.sort()
1755 self.assertEqual(keys, ['activity', 'actor', 'assignedto', 'creation',
1756 'creator', 'deadline', 'feedback', 'files', 'foo', 'id', 'messages',
1757 'nosy', 'priority', 'spam', 'status', 'superseder'])
1758 self.assertEqual(self.db.issue.list(), ['1'])
1760 def testAddRemoveProperty(self):
1761 self.db.issue.create(title="spam", status='1')
1762 self.db.commit()
1764 self.db.issue.addprop(fixer=Link("user"))
1765 del self.db.issue.properties['title']
1766 self.db.post_init()
1767 props = self.db.issue.getprops()
1768 keys = props.keys()
1769 keys.sort()
1770 self.assertEqual(keys, ['activity', 'actor', 'assignedto', 'creation',
1771 'creator', 'deadline', 'feedback', 'files', 'fixer', 'foo', 'id',
1772 'messages', 'nosy', 'priority', 'spam', 'status', 'superseder'])
1773 self.assertEqual(self.db.issue.list(), ['1'])
1775 def testNosyMail(self) :
1776 """Creates one issue with two attachments, one smaller and one larger
1777 than the set max_attachment_size.
1778 """
1779 db = self.db
1780 db.config.NOSY_MAX_ATTACHMENT_SIZE = 4096
1781 res = dict(mail_to = None, mail_msg = None)
1782 def dummy_snd(s, to, msg, res=res) :
1783 res["mail_to"], res["mail_msg"] = to, msg
1784 backup, Mailer.smtp_send = Mailer.smtp_send, dummy_snd
1785 try :
1786 f1 = db.file.create(name="test1.txt", content="x" * 20)
1787 f2 = db.file.create(name="test2.txt", content="y" * 5000)
1788 m = db.msg.create(content="one two", author="admin",
1789 files = [f1, f2])
1790 i = db.issue.create(title='spam', files = [f1, f2],
1791 messages = [m], nosy = [db.user.lookup("fred")])
1793 db.issue.nosymessage(i, m, {})
1794 mail_msg = res["mail_msg"].getvalue()
1795 self.assertEqual(res["mail_to"], ["fred@example.com"])
1796 self.failUnless("From: admin" in mail_msg)
1797 self.failUnless("Subject: [issue1] spam" in mail_msg)
1798 self.failUnless("New submission from admin" in mail_msg)
1799 self.failUnless("one two" in mail_msg)
1800 self.failIf("File 'test1.txt' not attached" in mail_msg)
1801 self.failUnless(base64.encodestring("xxx").rstrip() in mail_msg)
1802 self.failUnless("File 'test2.txt' not attached" in mail_msg)
1803 self.failIf(base64.encodestring("yyy").rstrip() in mail_msg)
1804 finally :
1805 Mailer.smtp_send = backup
1807 class ROTest(MyTestCase):
1808 def setUp(self):
1809 # remove previous test, ignore errors
1810 if os.path.exists(config.DATABASE):
1811 shutil.rmtree(config.DATABASE)
1812 os.makedirs(config.DATABASE + '/files')
1813 self.db = self.module.Database(config, 'admin')
1814 setupSchema(self.db, 1, self.module)
1815 self.db.close()
1817 self.db = self.module.Database(config)
1818 setupSchema(self.db, 0, self.module)
1820 def testExceptions(self):
1821 # this tests the exceptions that should be raised
1822 ar = self.assertRaises
1824 # this tests the exceptions that should be raised
1825 ar(DatabaseError, self.db.status.create, name="foo")
1826 ar(DatabaseError, self.db.status.set, '1', name="foo")
1827 ar(DatabaseError, self.db.status.retire, '1')
1830 class SchemaTest(MyTestCase):
1831 def setUp(self):
1832 # remove previous test, ignore errors
1833 if os.path.exists(config.DATABASE):
1834 shutil.rmtree(config.DATABASE)
1835 os.makedirs(config.DATABASE + '/files')
1837 def test_reservedProperties(self):
1838 self.db = self.module.Database(config, 'admin')
1839 self.assertRaises(ValueError, self.module.Class, self.db, "a",
1840 creation=String())
1841 self.assertRaises(ValueError, self.module.Class, self.db, "a",
1842 activity=String())
1843 self.assertRaises(ValueError, self.module.Class, self.db, "a",
1844 creator=String())
1845 self.assertRaises(ValueError, self.module.Class, self.db, "a",
1846 actor=String())
1848 def init_a(self):
1849 self.db = self.module.Database(config, 'admin')
1850 a = self.module.Class(self.db, "a", name=String())
1851 a.setkey("name")
1852 self.db.post_init()
1854 def test_fileClassProps(self):
1855 self.db = self.module.Database(config, 'admin')
1856 a = self.module.FileClass(self.db, 'a')
1857 l = a.getprops().keys()
1858 l.sort()
1859 self.assert_(l, ['activity', 'actor', 'content', 'created',
1860 'creation', 'type'])
1862 def init_ab(self):
1863 self.db = self.module.Database(config, 'admin')
1864 a = self.module.Class(self.db, "a", name=String())
1865 a.setkey("name")
1866 b = self.module.Class(self.db, "b", name=String(),
1867 fooz=Multilink('a'))
1868 b.setkey("name")
1869 self.db.post_init()
1871 def test_addNewClass(self):
1872 self.init_a()
1874 self.assertRaises(ValueError, self.module.Class, self.db, "a",
1875 name=String())
1877 aid = self.db.a.create(name='apple')
1878 self.db.commit(); self.db.close()
1880 # add a new class to the schema and check creation of new items
1881 # (and existence of old ones)
1882 self.init_ab()
1883 bid = self.db.b.create(name='bear', fooz=[aid])
1884 self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
1885 self.db.commit()
1886 self.db.close()
1888 # now check we can recall the added class' items
1889 self.init_ab()
1890 self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
1891 self.assertEqual(self.db.a.lookup('apple'), aid)
1892 self.assertEqual(self.db.b.get(bid, 'name'), 'bear')
1893 self.assertEqual(self.db.b.get(bid, 'fooz'), [aid])
1894 self.assertEqual(self.db.b.lookup('bear'), bid)
1896 # confirm journal's ok
1897 self.db.getjournal('a', aid)
1898 self.db.getjournal('b', bid)
1900 def init_amod(self):
1901 self.db = self.module.Database(config, 'admin')
1902 a = self.module.Class(self.db, "a", name=String(), newstr=String(),
1903 newint=Interval(), newnum=Number(), newbool=Boolean(),
1904 newdate=Date())
1905 a.setkey("name")
1906 b = self.module.Class(self.db, "b", name=String())
1907 b.setkey("name")
1908 self.db.post_init()
1910 def test_modifyClass(self):
1911 self.init_ab()
1913 # add item to user and issue class
1914 aid = self.db.a.create(name='apple')
1915 bid = self.db.b.create(name='bear')
1916 self.db.commit(); self.db.close()
1918 # modify "a" schema
1919 self.init_amod()
1920 self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
1921 self.assertEqual(self.db.a.get(aid, 'newstr'), None)
1922 self.assertEqual(self.db.a.get(aid, 'newint'), None)
1923 # hack - metakit can't return None for missing values, and we're not
1924 # really checking for that behavior here anyway
1925 self.assert_(not self.db.a.get(aid, 'newnum'))
1926 self.assert_(not self.db.a.get(aid, 'newbool'))
1927 self.assertEqual(self.db.a.get(aid, 'newdate'), None)
1928 self.assertEqual(self.db.b.get(aid, 'name'), 'bear')
1929 aid2 = self.db.a.create(name='aardvark', newstr='booz')
1930 self.db.commit(); self.db.close()
1932 # test
1933 self.init_amod()
1934 self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
1935 self.assertEqual(self.db.a.get(aid, 'newstr'), None)
1936 self.assertEqual(self.db.b.get(aid, 'name'), 'bear')
1937 self.assertEqual(self.db.a.get(aid2, 'name'), 'aardvark')
1938 self.assertEqual(self.db.a.get(aid2, 'newstr'), 'booz')
1940 # confirm journal's ok
1941 self.db.getjournal('a', aid)
1942 self.db.getjournal('a', aid2)
1944 def init_amodkey(self):
1945 self.db = self.module.Database(config, 'admin')
1946 a = self.module.Class(self.db, "a", name=String(), newstr=String())
1947 a.setkey("newstr")
1948 b = self.module.Class(self.db, "b", name=String())
1949 b.setkey("name")
1950 self.db.post_init()
1952 def test_changeClassKey(self):
1953 self.init_amod()
1954 aid = self.db.a.create(name='apple')
1955 self.assertEqual(self.db.a.lookup('apple'), aid)
1956 self.db.commit(); self.db.close()
1958 # change the key to newstr on a
1959 self.init_amodkey()
1960 self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
1961 self.assertEqual(self.db.a.get(aid, 'newstr'), None)
1962 self.assertRaises(KeyError, self.db.a.lookup, 'apple')
1963 aid2 = self.db.a.create(name='aardvark', newstr='booz')
1964 self.db.commit(); self.db.close()
1966 # check
1967 self.init_amodkey()
1968 self.assertEqual(self.db.a.lookup('booz'), aid2)
1970 # confirm journal's ok
1971 self.db.getjournal('a', aid)
1973 def test_removeClassKey(self):
1974 self.init_amod()
1975 aid = self.db.a.create(name='apple')
1976 self.assertEqual(self.db.a.lookup('apple'), aid)
1977 self.db.commit(); self.db.close()
1979 self.db = self.module.Database(config, 'admin')
1980 a = self.module.Class(self.db, "a", name=String(), newstr=String())
1981 self.db.post_init()
1983 aid2 = self.db.a.create(name='apple', newstr='booz')
1984 self.db.commit()
1987 def init_amodml(self):
1988 self.db = self.module.Database(config, 'admin')
1989 a = self.module.Class(self.db, "a", name=String(),
1990 newml=Multilink('a'))
1991 a.setkey('name')
1992 self.db.post_init()
1994 def test_makeNewMultilink(self):
1995 self.init_a()
1996 aid = self.db.a.create(name='apple')
1997 self.assertEqual(self.db.a.lookup('apple'), aid)
1998 self.db.commit(); self.db.close()
2000 # add a multilink prop
2001 self.init_amodml()
2002 bid = self.db.a.create(name='bear', newml=[aid])
2003 self.assertEqual(self.db.a.find(newml=aid), [bid])
2004 self.assertEqual(self.db.a.lookup('apple'), aid)
2005 self.db.commit(); self.db.close()
2007 # check
2008 self.init_amodml()
2009 self.assertEqual(self.db.a.find(newml=aid), [bid])
2010 self.assertEqual(self.db.a.lookup('apple'), aid)
2011 self.assertEqual(self.db.a.lookup('bear'), bid)
2013 # confirm journal's ok
2014 self.db.getjournal('a', aid)
2015 self.db.getjournal('a', bid)
2017 def test_removeMultilink(self):
2018 # add a multilink prop
2019 self.init_amodml()
2020 aid = self.db.a.create(name='apple')
2021 bid = self.db.a.create(name='bear', newml=[aid])
2022 self.assertEqual(self.db.a.find(newml=aid), [bid])
2023 self.assertEqual(self.db.a.lookup('apple'), aid)
2024 self.assertEqual(self.db.a.lookup('bear'), bid)
2025 self.db.commit(); self.db.close()
2027 # remove the multilink
2028 self.init_a()
2029 self.assertEqual(self.db.a.lookup('apple'), aid)
2030 self.assertEqual(self.db.a.lookup('bear'), bid)
2032 # confirm journal's ok
2033 self.db.getjournal('a', aid)
2034 self.db.getjournal('a', bid)
2036 def test_removeClass(self):
2037 self.init_ab()
2038 aid = self.db.a.create(name='apple')
2039 bid = self.db.b.create(name='bear')
2040 self.db.commit(); self.db.close()
2042 # drop the b class
2043 self.init_a()
2044 self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
2045 self.assertEqual(self.db.a.lookup('apple'), aid)
2046 self.db.commit(); self.db.close()
2048 # now check we can recall the added class' items
2049 self.init_a()
2050 self.assertEqual(self.db.a.get(aid, 'name'), 'apple')
2051 self.assertEqual(self.db.a.lookup('apple'), aid)
2053 # confirm journal's ok
2054 self.db.getjournal('a', aid)
2056 class RDBMSTest:
2057 ''' tests specific to RDBMS backends '''
2058 def test_indexTest(self):
2059 self.assertEqual(self.db.sql_index_exists('_issue', '_issue_id_idx'), 1)
2060 self.assertEqual(self.db.sql_index_exists('_issue', '_issue_x_idx'), 0)
2063 class ClassicInitTest(unittest.TestCase):
2064 count = 0
2065 db = None
2067 def setUp(self):
2068 ClassicInitTest.count = ClassicInitTest.count + 1
2069 self.dirname = '_test_init_%s'%self.count
2070 try:
2071 shutil.rmtree(self.dirname)
2072 except OSError, error:
2073 if error.errno not in (errno.ENOENT, errno.ESRCH): raise
2075 def testCreation(self):
2076 ae = self.assertEqual
2078 # set up and open a tracker
2079 tracker = setupTracker(self.dirname, self.backend)
2080 # open the database
2081 db = self.db = tracker.open('test')
2083 # check the basics of the schema and initial data set
2084 l = db.priority.list()
2085 l.sort()
2086 ae(l, ['1', '2', '3', '4', '5'])
2087 l = db.status.list()
2088 l.sort()
2089 ae(l, ['1', '2', '3', '4', '5', '6', '7', '8'])
2090 l = db.keyword.list()
2091 ae(l, [])
2092 l = db.user.list()
2093 l.sort()
2094 ae(l, ['1', '2'])
2095 l = db.msg.list()
2096 ae(l, [])
2097 l = db.file.list()
2098 ae(l, [])
2099 l = db.issue.list()
2100 ae(l, [])
2102 def tearDown(self):
2103 if self.db is not None:
2104 self.db.close()
2105 try:
2106 shutil.rmtree(self.dirname)
2107 except OSError, error:
2108 if error.errno not in (errno.ENOENT, errno.ESRCH): raise
2110 # vim: set et sts=4 sw=4 :