blob: 04e856fcfe7387b373832b1992d3049ec619dda5 [file] [log] [blame]
Fred Drake0aaed272000-10-23 13:39:15 +00001import os
Fred Drakec02bc3e2001-05-21 20:23:21 +00002import time
Thomas Wouters477c8d52006-05-27 19:21:47 +00003import stat
4import socket
5import email
6import email.Message
7import rfc822
8import re
9import StringIO
Barry Warsaw04f357c2002-07-23 19:04:11 +000010from test import test_support
Thomas Wouters477c8d52006-05-27 19:21:47 +000011import unittest
12import mailbox
13import glob
Guido van Rossum75ebb292001-04-10 15:01:20 +000014try:
Thomas Wouters477c8d52006-05-27 19:21:47 +000015 import fcntl
16except ImportError:
Guido van Rossum75ebb292001-04-10 15:01:20 +000017 pass
18
Thomas Wouters477c8d52006-05-27 19:21:47 +000019
20class TestBase(unittest.TestCase):
21
22 def _check_sample(self, msg):
23 # Inspect a mailbox.Message representation of the sample message
24 self.assert_(isinstance(msg, email.Message.Message))
25 self.assert_(isinstance(msg, mailbox.Message))
26 for key, value in _sample_headers.iteritems():
27 self.assert_(value in msg.get_all(key))
28 self.assert_(msg.is_multipart())
29 self.assert_(len(msg.get_payload()) == len(_sample_payloads))
30 for i, payload in enumerate(_sample_payloads):
31 part = msg.get_payload(i)
32 self.assert_(isinstance(part, email.Message.Message))
33 self.assert_(not isinstance(part, mailbox.Message))
34 self.assert_(part.get_payload() == payload)
35
36 def _delete_recursively(self, target):
37 # Delete a file or delete a directory recursively
38 if os.path.isdir(target):
39 for path, dirs, files in os.walk(target, topdown=False):
40 for name in files:
41 os.remove(os.path.join(path, name))
42 for name in dirs:
43 os.rmdir(os.path.join(path, name))
44 os.rmdir(target)
45 elif os.path.exists(target):
46 os.remove(target)
47
48
49class TestMailbox(TestBase):
50
51 _factory = None # Overridden by subclasses to reuse tests
52 _template = 'From: foo\n\n%s'
53
54 def setUp(self):
55 self._path = test_support.TESTFN
56 self._box = self._factory(self._path)
57
58 def tearDown(self):
59 self._box.close()
60 self._delete_recursively(self._path)
61
62 def test_add(self):
63 # Add copies of a sample message
64 keys = []
65 keys.append(self._box.add(self._template % 0))
66 self.assert_(len(self._box) == 1)
67 keys.append(self._box.add(mailbox.Message(_sample_message)))
68 self.assert_(len(self._box) == 2)
69 keys.append(self._box.add(email.message_from_string(_sample_message)))
70 self.assert_(len(self._box) == 3)
71 keys.append(self._box.add(StringIO.StringIO(_sample_message)))
72 self.assert_(len(self._box) == 4)
73 keys.append(self._box.add(_sample_message))
74 self.assert_(len(self._box) == 5)
75 self.assert_(self._box.get_string(keys[0]) == self._template % 0)
76 for i in (1, 2, 3, 4):
77 self._check_sample(self._box[keys[i]])
78
79 def test_remove(self):
80 # Remove messages using remove()
81 self._test_remove_or_delitem(self._box.remove)
82
83 def test_delitem(self):
84 # Remove messages using __delitem__()
85 self._test_remove_or_delitem(self._box.__delitem__)
86
87 def _test_remove_or_delitem(self, method):
88 # (Used by test_remove() and test_delitem().)
89 key0 = self._box.add(self._template % 0)
90 key1 = self._box.add(self._template % 1)
91 self.assert_(len(self._box) == 2)
92 method(key0)
93 l = len(self._box)
94 self.assert_(l == 1, "actual l: %s" % l)
95 self.assertRaises(KeyError, lambda: self._box[key0])
96 self.assertRaises(KeyError, lambda: method(key0))
97 self.assert_(self._box.get_string(key1) == self._template % 1)
98 key2 = self._box.add(self._template % 2)
99 self.assert_(len(self._box) == 2)
100 method(key2)
101 l = len(self._box)
102 self.assert_(l == 1, "actual l: %s" % l)
103 self.assertRaises(KeyError, lambda: self._box[key2])
104 self.assertRaises(KeyError, lambda: method(key2))
105 self.assert_(self._box.get_string(key1) == self._template % 1)
106 method(key1)
107 self.assert_(len(self._box) == 0)
108 self.assertRaises(KeyError, lambda: self._box[key1])
109 self.assertRaises(KeyError, lambda: method(key1))
110
111 def test_discard(self, repetitions=10):
112 # Discard messages
113 key0 = self._box.add(self._template % 0)
114 key1 = self._box.add(self._template % 1)
115 self.assert_(len(self._box) == 2)
116 self._box.discard(key0)
117 self.assert_(len(self._box) == 1)
118 self.assertRaises(KeyError, lambda: self._box[key0])
119 self._box.discard(key0)
120 self.assert_(len(self._box) == 1)
121 self.assertRaises(KeyError, lambda: self._box[key0])
122
123 def test_get(self):
124 # Retrieve messages using get()
125 key0 = self._box.add(self._template % 0)
126 msg = self._box.get(key0)
127 self.assert_(msg['from'] == 'foo')
128 self.assert_(msg.get_payload() == '0')
129 self.assert_(self._box.get('foo') is None)
130 self.assert_(self._box.get('foo', False) is False)
131 self._box.close()
132 self._box = self._factory(self._path, factory=rfc822.Message)
133 key1 = self._box.add(self._template % 1)
134 msg = self._box.get(key1)
135 self.assert_(msg['from'] == 'foo')
136 self.assert_(msg.fp.read() == '1')
137
138 def test_getitem(self):
139 # Retrieve message using __getitem__()
140 key0 = self._box.add(self._template % 0)
141 msg = self._box[key0]
142 self.assert_(msg['from'] == 'foo')
143 self.assert_(msg.get_payload() == '0')
144 self.assertRaises(KeyError, lambda: self._box['foo'])
145 self._box.discard(key0)
146 self.assertRaises(KeyError, lambda: self._box[key0])
147
148 def test_get_message(self):
149 # Get Message representations of messages
150 key0 = self._box.add(self._template % 0)
151 key1 = self._box.add(_sample_message)
152 msg0 = self._box.get_message(key0)
153 self.assert_(isinstance(msg0, mailbox.Message))
154 self.assert_(msg0['from'] == 'foo')
155 self.assert_(msg0.get_payload() == '0')
156 self._check_sample(self._box.get_message(key1))
157
158 def test_get_string(self):
159 # Get string representations of messages
160 key0 = self._box.add(self._template % 0)
161 key1 = self._box.add(_sample_message)
162 self.assert_(self._box.get_string(key0) == self._template % 0)
163 self.assert_(self._box.get_string(key1) == _sample_message)
164
165 def test_get_file(self):
166 # Get file representations of messages
167 key0 = self._box.add(self._template % 0)
168 key1 = self._box.add(_sample_message)
169 self.assert_(self._box.get_file(key0).read().replace(os.linesep, '\n')
170 == self._template % 0)
171 self.assert_(self._box.get_file(key1).read().replace(os.linesep, '\n')
172 == _sample_message)
173
174 def test_iterkeys(self):
175 # Get keys using iterkeys()
176 self._check_iteration(self._box.iterkeys, do_keys=True, do_values=False)
177
178 def test_keys(self):
179 # Get keys using keys()
180 self._check_iteration(self._box.keys, do_keys=True, do_values=False)
181
182 def test_itervalues(self):
183 # Get values using itervalues()
184 self._check_iteration(self._box.itervalues, do_keys=False,
185 do_values=True)
186
187 def test_iter(self):
188 # Get values using __iter__()
189 self._check_iteration(self._box.__iter__, do_keys=False,
190 do_values=True)
191
192 def test_values(self):
193 # Get values using values()
194 self._check_iteration(self._box.values, do_keys=False, do_values=True)
195
196 def test_iteritems(self):
197 # Get keys and values using iteritems()
198 self._check_iteration(self._box.iteritems, do_keys=True,
199 do_values=True)
200
201 def test_items(self):
202 # Get keys and values using items()
203 self._check_iteration(self._box.items, do_keys=True, do_values=True)
204
205 def _check_iteration(self, method, do_keys, do_values, repetitions=10):
206 for value in method():
207 self.fail("Not empty")
208 keys, values = [], []
209 for i in xrange(repetitions):
210 keys.append(self._box.add(self._template % i))
211 values.append(self._template % i)
212 if do_keys and not do_values:
213 returned_keys = list(method())
214 elif do_values and not do_keys:
215 returned_values = list(method())
216 else:
217 returned_keys, returned_values = [], []
218 for key, value in method():
219 returned_keys.append(key)
220 returned_values.append(value)
221 if do_keys:
222 self.assert_(len(keys) == len(returned_keys))
223 self.assert_(set(keys) == set(returned_keys))
224 if do_values:
225 count = 0
226 for value in returned_values:
227 self.assert_(value['from'] == 'foo')
228 self.assert_(int(value.get_payload()) < repetitions)
229 count += 1
230 self.assert_(len(values) == count)
231
Thomas Wouters477c8d52006-05-27 19:21:47 +0000232 def test_contains(self):
233 # Check existence of keys using __contains__()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000234 method = self._box.__contains__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000235 self.assert_(not method('foo'))
236 key0 = self._box.add(self._template % 0)
237 self.assert_(method(key0))
238 self.assert_(not method('foo'))
239 key1 = self._box.add(self._template % 1)
240 self.assert_(method(key1))
241 self.assert_(method(key0))
242 self.assert_(not method('foo'))
243 self._box.remove(key0)
244 self.assert_(not method(key0))
245 self.assert_(method(key1))
246 self.assert_(not method('foo'))
247 self._box.remove(key1)
248 self.assert_(not method(key1))
249 self.assert_(not method(key0))
250 self.assert_(not method('foo'))
251
252 def test_len(self, repetitions=10):
253 # Get message count
254 keys = []
255 for i in xrange(repetitions):
256 self.assert_(len(self._box) == i)
257 keys.append(self._box.add(self._template % i))
258 self.assert_(len(self._box) == i + 1)
259 for i in xrange(repetitions):
260 self.assert_(len(self._box) == repetitions - i)
261 self._box.remove(keys[i])
262 self.assert_(len(self._box) == repetitions - i - 1)
263
264 def test_set_item(self):
265 # Modify messages using __setitem__()
266 key0 = self._box.add(self._template % 'original 0')
267 self.assert_(self._box.get_string(key0) == \
268 self._template % 'original 0')
269 key1 = self._box.add(self._template % 'original 1')
270 self.assert_(self._box.get_string(key1) == \
271 self._template % 'original 1')
272 self._box[key0] = self._template % 'changed 0'
273 self.assert_(self._box.get_string(key0) == \
274 self._template % 'changed 0')
275 self._box[key1] = self._template % 'changed 1'
276 self.assert_(self._box.get_string(key1) == \
277 self._template % 'changed 1')
278 self._box[key0] = _sample_message
279 self._check_sample(self._box[key0])
280 self._box[key1] = self._box[key0]
281 self._check_sample(self._box[key1])
282 self._box[key0] = self._template % 'original 0'
283 self.assert_(self._box.get_string(key0) ==
284 self._template % 'original 0')
285 self._check_sample(self._box[key1])
286 self.assertRaises(KeyError,
287 lambda: self._box.__setitem__('foo', 'bar'))
288 self.assertRaises(KeyError, lambda: self._box['foo'])
289 self.assert_(len(self._box) == 2)
290
291 def test_clear(self, iterations=10):
292 # Remove all messages using clear()
293 keys = []
294 for i in xrange(iterations):
295 self._box.add(self._template % i)
296 for i, key in enumerate(keys):
297 self.assert_(self._box.get_string(key) == self._template % i)
298 self._box.clear()
299 self.assert_(len(self._box) == 0)
300 for i, key in enumerate(keys):
301 self.assertRaises(KeyError, lambda: self._box.get_string(key))
302
303 def test_pop(self):
304 # Get and remove a message using pop()
305 key0 = self._box.add(self._template % 0)
306 self.assert_(key0 in self._box)
307 key1 = self._box.add(self._template % 1)
308 self.assert_(key1 in self._box)
309 self.assert_(self._box.pop(key0).get_payload() == '0')
310 self.assert_(key0 not in self._box)
311 self.assert_(key1 in self._box)
312 key2 = self._box.add(self._template % 2)
313 self.assert_(key2 in self._box)
314 self.assert_(self._box.pop(key2).get_payload() == '2')
315 self.assert_(key2 not in self._box)
316 self.assert_(key1 in self._box)
317 self.assert_(self._box.pop(key1).get_payload() == '1')
318 self.assert_(key1 not in self._box)
319 self.assert_(len(self._box) == 0)
320
321 def test_popitem(self, iterations=10):
322 # Get and remove an arbitrary (key, message) using popitem()
323 keys = []
324 for i in xrange(10):
325 keys.append(self._box.add(self._template % i))
326 seen = []
327 for i in xrange(10):
328 key, msg = self._box.popitem()
329 self.assert_(key in keys)
330 self.assert_(key not in seen)
331 seen.append(key)
332 self.assert_(int(msg.get_payload()) == keys.index(key))
333 self.assert_(len(self._box) == 0)
334 for key in keys:
335 self.assertRaises(KeyError, lambda: self._box[key])
336
337 def test_update(self):
338 # Modify multiple messages using update()
339 key0 = self._box.add(self._template % 'original 0')
340 key1 = self._box.add(self._template % 'original 1')
341 key2 = self._box.add(self._template % 'original 2')
342 self._box.update({key0: self._template % 'changed 0',
343 key2: _sample_message})
344 self.assert_(len(self._box) == 3)
345 self.assert_(self._box.get_string(key0) ==
346 self._template % 'changed 0')
347 self.assert_(self._box.get_string(key1) ==
348 self._template % 'original 1')
349 self._check_sample(self._box[key2])
350 self._box.update([(key2, self._template % 'changed 2'),
351 (key1, self._template % 'changed 1'),
352 (key0, self._template % 'original 0')])
353 self.assert_(len(self._box) == 3)
354 self.assert_(self._box.get_string(key0) ==
355 self._template % 'original 0')
356 self.assert_(self._box.get_string(key1) ==
357 self._template % 'changed 1')
358 self.assert_(self._box.get_string(key2) ==
359 self._template % 'changed 2')
360 self.assertRaises(KeyError,
361 lambda: self._box.update({'foo': 'bar',
362 key0: self._template % "changed 0"}))
363 self.assert_(len(self._box) == 3)
364 self.assert_(self._box.get_string(key0) ==
365 self._template % "changed 0")
366 self.assert_(self._box.get_string(key1) ==
367 self._template % "changed 1")
368 self.assert_(self._box.get_string(key2) ==
369 self._template % "changed 2")
370
371 def test_flush(self):
372 # Write changes to disk
373 self._test_flush_or_close(self._box.flush)
374
375 def test_lock_unlock(self):
376 # Lock and unlock the mailbox
377 self.assert_(not os.path.exists(self._get_lock_path()))
378 self._box.lock()
379 self.assert_(os.path.exists(self._get_lock_path()))
380 self._box.unlock()
381 self.assert_(not os.path.exists(self._get_lock_path()))
382
383 def test_close(self):
384 # Close mailbox and flush changes to disk
385 self._test_flush_or_close(self._box.close)
386
387 def _test_flush_or_close(self, method):
388 contents = [self._template % i for i in xrange(3)]
389 self._box.add(contents[0])
390 self._box.add(contents[1])
391 self._box.add(contents[2])
392 method()
393 self._box = self._factory(self._path)
394 keys = self._box.keys()
395 self.assert_(len(keys) == 3)
396 for key in keys:
397 self.assert_(self._box.get_string(key) in contents)
398
399 def test_dump_message(self):
400 # Write message representations to disk
401 for input in (email.message_from_string(_sample_message),
402 _sample_message, StringIO.StringIO(_sample_message)):
403 output = StringIO.StringIO()
404 self._box._dump_message(input, output)
405 self.assert_(output.getvalue() ==
406 _sample_message.replace('\n', os.linesep))
407 output = StringIO.StringIO()
408 self.assertRaises(TypeError,
409 lambda: self._box._dump_message(None, output))
410
411 def _get_lock_path(self):
412 # Return the path of the dot lock file. May be overridden.
413 return self._path + '.lock'
414
415
416class TestMailboxSuperclass(TestBase):
417
418 def test_notimplemented(self):
419 # Test that all Mailbox methods raise NotImplementedException.
420 box = mailbox.Mailbox('path')
421 self.assertRaises(NotImplementedError, lambda: box.add(''))
422 self.assertRaises(NotImplementedError, lambda: box.remove(''))
423 self.assertRaises(NotImplementedError, lambda: box.__delitem__(''))
424 self.assertRaises(NotImplementedError, lambda: box.discard(''))
425 self.assertRaises(NotImplementedError, lambda: box.__setitem__('', ''))
426 self.assertRaises(NotImplementedError, lambda: box.iterkeys())
427 self.assertRaises(NotImplementedError, lambda: box.keys())
428 self.assertRaises(NotImplementedError, lambda: box.itervalues().next())
429 self.assertRaises(NotImplementedError, lambda: box.__iter__().next())
430 self.assertRaises(NotImplementedError, lambda: box.values())
431 self.assertRaises(NotImplementedError, lambda: box.iteritems().next())
432 self.assertRaises(NotImplementedError, lambda: box.items())
433 self.assertRaises(NotImplementedError, lambda: box.get(''))
434 self.assertRaises(NotImplementedError, lambda: box.__getitem__(''))
435 self.assertRaises(NotImplementedError, lambda: box.get_message(''))
436 self.assertRaises(NotImplementedError, lambda: box.get_string(''))
437 self.assertRaises(NotImplementedError, lambda: box.get_file(''))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000438 self.assertRaises(NotImplementedError, lambda: '' in box)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439 self.assertRaises(NotImplementedError, lambda: box.__contains__(''))
440 self.assertRaises(NotImplementedError, lambda: box.__len__())
441 self.assertRaises(NotImplementedError, lambda: box.clear())
442 self.assertRaises(NotImplementedError, lambda: box.pop(''))
443 self.assertRaises(NotImplementedError, lambda: box.popitem())
444 self.assertRaises(NotImplementedError, lambda: box.update((('', ''),)))
445 self.assertRaises(NotImplementedError, lambda: box.flush())
446 self.assertRaises(NotImplementedError, lambda: box.lock())
447 self.assertRaises(NotImplementedError, lambda: box.unlock())
448 self.assertRaises(NotImplementedError, lambda: box.close())
449
450
451class TestMaildir(TestMailbox):
452
453 _factory = lambda self, path, factory=None: mailbox.Maildir(path, factory)
454
455 def setUp(self):
456 TestMailbox.setUp(self)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000457 if os.name in ('nt', 'os2'):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000458 self._box.colon = '!'
459
460 def test_add_MM(self):
461 # Add a MaildirMessage instance
462 msg = mailbox.MaildirMessage(self._template % 0)
463 msg.set_subdir('cur')
464 msg.set_info('foo')
465 key = self._box.add(msg)
466 self.assert_(os.path.exists(os.path.join(self._path, 'cur', '%s%sfoo' %
467 (key, self._box.colon))))
468
469 def test_get_MM(self):
470 # Get a MaildirMessage instance
471 msg = mailbox.MaildirMessage(self._template % 0)
472 msg.set_subdir('cur')
473 msg.set_flags('RF')
474 key = self._box.add(msg)
475 msg_returned = self._box.get_message(key)
476 self.assert_(isinstance(msg_returned, mailbox.MaildirMessage))
477 self.assert_(msg_returned.get_subdir() == 'cur')
478 self.assert_(msg_returned.get_flags() == 'FR')
479
480 def test_set_MM(self):
481 # Set with a MaildirMessage instance
482 msg0 = mailbox.MaildirMessage(self._template % 0)
483 msg0.set_flags('TP')
484 key = self._box.add(msg0)
485 msg_returned = self._box.get_message(key)
486 self.assert_(msg_returned.get_subdir() == 'new')
487 self.assert_(msg_returned.get_flags() == 'PT')
488 msg1 = mailbox.MaildirMessage(self._template % 1)
489 self._box[key] = msg1
490 msg_returned = self._box.get_message(key)
491 self.assert_(msg_returned.get_subdir() == 'new')
492 self.assert_(msg_returned.get_flags() == '')
493 self.assert_(msg_returned.get_payload() == '1')
494 msg2 = mailbox.MaildirMessage(self._template % 2)
495 msg2.set_info('2,S')
496 self._box[key] = msg2
497 self._box[key] = self._template % 3
498 msg_returned = self._box.get_message(key)
499 self.assert_(msg_returned.get_subdir() == 'new')
500 self.assert_(msg_returned.get_flags() == 'S')
501 self.assert_(msg_returned.get_payload() == '3')
502
503 def test_initialize_new(self):
504 # Initialize a non-existent mailbox
505 self.tearDown()
506 self._box = mailbox.Maildir(self._path)
507 self._check_basics(factory=rfc822.Message)
508 self._delete_recursively(self._path)
509 self._box = self._factory(self._path, factory=None)
510 self._check_basics()
511
512 def test_initialize_existing(self):
513 # Initialize an existing mailbox
514 self.tearDown()
515 for subdir in '', 'tmp', 'new', 'cur':
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000516 os.mkdir(os.path.normpath(os.path.join(self._path, subdir)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000517 self._box = mailbox.Maildir(self._path)
518 self._check_basics(factory=rfc822.Message)
519 self._box = mailbox.Maildir(self._path, factory=None)
520 self._check_basics()
521
522 def _check_basics(self, factory=None):
523 # (Used by test_open_new() and test_open_existing().)
524 self.assertEqual(self._box._path, os.path.abspath(self._path))
525 self.assertEqual(self._box._factory, factory)
526 for subdir in '', 'tmp', 'new', 'cur':
527 path = os.path.join(self._path, subdir)
528 mode = os.stat(path)[stat.ST_MODE]
529 self.assert_(stat.S_ISDIR(mode), "Not a directory: '%s'" % path)
530
531 def test_list_folders(self):
532 # List folders
533 self._box.add_folder('one')
534 self._box.add_folder('two')
535 self._box.add_folder('three')
536 self.assert_(len(self._box.list_folders()) == 3)
537 self.assert_(set(self._box.list_folders()) ==
538 set(('one', 'two', 'three')))
539
540 def test_get_folder(self):
541 # Open folders
542 self._box.add_folder('foo.bar')
543 folder0 = self._box.get_folder('foo.bar')
544 folder0.add(self._template % 'bar')
545 self.assert_(os.path.isdir(os.path.join(self._path, '.foo.bar')))
546 folder1 = self._box.get_folder('foo.bar')
547 self.assert_(folder1.get_string(folder1.keys()[0]) == \
548 self._template % 'bar')
549
550 def test_add_and_remove_folders(self):
551 # Delete folders
552 self._box.add_folder('one')
553 self._box.add_folder('two')
554 self.assert_(len(self._box.list_folders()) == 2)
555 self.assert_(set(self._box.list_folders()) == set(('one', 'two')))
556 self._box.remove_folder('one')
557 self.assert_(len(self._box.list_folders()) == 1)
558 self.assert_(set(self._box.list_folders()) == set(('two',)))
559 self._box.add_folder('three')
560 self.assert_(len(self._box.list_folders()) == 2)
561 self.assert_(set(self._box.list_folders()) == set(('two', 'three')))
562 self._box.remove_folder('three')
563 self.assert_(len(self._box.list_folders()) == 1)
564 self.assert_(set(self._box.list_folders()) == set(('two',)))
565 self._box.remove_folder('two')
566 self.assert_(len(self._box.list_folders()) == 0)
567 self.assert_(self._box.list_folders() == [])
568
569 def test_clean(self):
570 # Remove old files from 'tmp'
571 foo_path = os.path.join(self._path, 'tmp', 'foo')
572 bar_path = os.path.join(self._path, 'tmp', 'bar')
573 f = open(foo_path, 'w')
574 f.write("@")
575 f.close()
576 f = open(bar_path, 'w')
577 f.write("@")
578 f.close()
579 self._box.clean()
580 self.assert_(os.path.exists(foo_path))
581 self.assert_(os.path.exists(bar_path))
582 foo_stat = os.stat(foo_path)
583 os.utime(foo_path, (time.time() - 129600 - 2,
584 foo_stat.st_mtime))
585 self._box.clean()
586 self.assert_(not os.path.exists(foo_path))
587 self.assert_(os.path.exists(bar_path))
588
589 def test_create_tmp(self, repetitions=10):
590 # Create files in tmp directory
591 hostname = socket.gethostname()
592 if '/' in hostname:
593 hostname = hostname.replace('/', r'\057')
594 if ':' in hostname:
595 hostname = hostname.replace(':', r'\072')
596 pid = os.getpid()
597 pattern = re.compile(r"(?P<time>\d+)\.M(?P<M>\d{1,6})P(?P<P>\d+)"
598 r"Q(?P<Q>\d+)\.(?P<host>[^:/]+)")
599 previous_groups = None
600 for x in xrange(repetitions):
601 tmp_file = self._box._create_tmp()
602 head, tail = os.path.split(tmp_file.name)
603 self.assertEqual(head, os.path.abspath(os.path.join(self._path,
604 "tmp")),
605 "File in wrong location: '%s'" % head)
606 match = pattern.match(tail)
607 self.assert_(match != None, "Invalid file name: '%s'" % tail)
608 groups = match.groups()
609 if previous_groups != None:
610 self.assert_(int(groups[0] >= previous_groups[0]),
611 "Non-monotonic seconds: '%s' before '%s'" %
612 (previous_groups[0], groups[0]))
613 self.assert_(int(groups[1] >= previous_groups[1]) or
614 groups[0] != groups[1],
615 "Non-monotonic milliseconds: '%s' before '%s'" %
616 (previous_groups[1], groups[1]))
617 self.assert_(int(groups[2]) == pid,
618 "Process ID mismatch: '%s' should be '%s'" %
619 (groups[2], pid))
620 self.assert_(int(groups[3]) == int(previous_groups[3]) + 1,
621 "Non-sequential counter: '%s' before '%s'" %
622 (previous_groups[3], groups[3]))
623 self.assert_(groups[4] == hostname,
624 "Host name mismatch: '%s' should be '%s'" %
625 (groups[4], hostname))
626 previous_groups = groups
627 tmp_file.write(_sample_message)
628 tmp_file.seek(0)
629 self.assert_(tmp_file.read() == _sample_message)
630 tmp_file.close()
631 file_count = len(os.listdir(os.path.join(self._path, "tmp")))
632 self.assert_(file_count == repetitions,
633 "Wrong file count: '%s' should be '%s'" %
634 (file_count, repetitions))
635
636 def test_refresh(self):
637 # Update the table of contents
638 self.assert_(self._box._toc == {})
639 key0 = self._box.add(self._template % 0)
640 key1 = self._box.add(self._template % 1)
641 self.assert_(self._box._toc == {})
642 self._box._refresh()
643 self.assert_(self._box._toc == {key0: os.path.join('new', key0),
644 key1: os.path.join('new', key1)})
645 key2 = self._box.add(self._template % 2)
646 self.assert_(self._box._toc == {key0: os.path.join('new', key0),
647 key1: os.path.join('new', key1)})
648 self._box._refresh()
649 self.assert_(self._box._toc == {key0: os.path.join('new', key0),
650 key1: os.path.join('new', key1),
651 key2: os.path.join('new', key2)})
652
653 def test_lookup(self):
654 # Look up message subpaths in the TOC
655 self.assertRaises(KeyError, lambda: self._box._lookup('foo'))
656 key0 = self._box.add(self._template % 0)
657 self.assert_(self._box._lookup(key0) == os.path.join('new', key0))
658 os.remove(os.path.join(self._path, 'new', key0))
659 self.assert_(self._box._toc == {key0: os.path.join('new', key0)})
660 self.assertRaises(KeyError, lambda: self._box._lookup(key0))
661 self.assert_(self._box._toc == {})
662
663 def test_lock_unlock(self):
664 # Lock and unlock the mailbox. For Maildir, this does nothing.
665 self._box.lock()
666 self._box.unlock()
667
668
669class _TestMboxMMDF(TestMailbox):
670
671 def tearDown(self):
672 self._box.close()
673 self._delete_recursively(self._path)
674 for lock_remnant in glob.glob(self._path + '.*'):
675 os.remove(lock_remnant)
676
677 def test_add_from_string(self):
678 # Add a string starting with 'From ' to the mailbox
679 key = self._box.add('From foo@bar blah\nFrom: foo\n\n0')
680 self.assert_(self._box[key].get_from() == 'foo@bar blah')
681 self.assert_(self._box[key].get_payload() == '0')
682
683 def test_add_mbox_or_mmdf_message(self):
684 # Add an mboxMessage or MMDFMessage
685 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
686 msg = class_('From foo@bar blah\nFrom: foo\n\n0')
687 key = self._box.add(msg)
688
689 def test_open_close_open(self):
690 # Open and inspect previously-created mailbox
691 values = [self._template % i for i in xrange(3)]
692 for value in values:
693 self._box.add(value)
694 self._box.close()
695 mtime = os.path.getmtime(self._path)
696 self._box = self._factory(self._path)
697 self.assert_(len(self._box) == 3)
698 for key in self._box.iterkeys():
699 self.assert_(self._box.get_string(key) in values)
700 self._box.close()
701 self.assert_(mtime == os.path.getmtime(self._path))
702
703 def test_add_and_close(self):
704 # Verifying that closing a mailbox doesn't change added items
705 self._box.add(_sample_message)
706 for i in xrange(3):
707 self._box.add(self._template % i)
708 self._box.add(_sample_message)
709 self._box._file.flush()
710 self._box._file.seek(0)
711 contents = self._box._file.read()
712 self._box.close()
713 self.assert_(contents == open(self._path, 'rb').read())
714 self._box = self._factory(self._path)
715
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000716 def test_lock_conflict(self):
717 # Fork off a subprocess that will lock the file for 2 seconds,
718 # unlock it, and then exit.
719 if not hasattr(os, 'fork'):
720 return
721 pid = os.fork()
722 if pid == 0:
723 # In the child, lock the mailbox.
724 self._box.lock()
725 time.sleep(2)
726 self._box.unlock()
727 os._exit(0)
728
729 # In the parent, sleep a bit to give the child time to acquire
730 # the lock.
731 time.sleep(0.5)
732 self.assertRaises(mailbox.ExternalClashError,
733 self._box.lock)
734
735 # Wait for child to exit. Locking should now succeed.
736 exited_pid, status = os.waitpid(pid, 0)
737 self._box.lock()
738 self._box.unlock()
739
Thomas Wouters477c8d52006-05-27 19:21:47 +0000740
741class TestMbox(_TestMboxMMDF):
742
743 _factory = lambda self, path, factory=None: mailbox.mbox(path, factory)
744
745
746class TestMMDF(_TestMboxMMDF):
747
748 _factory = lambda self, path, factory=None: mailbox.MMDF(path, factory)
749
750
751class TestMH(TestMailbox):
752
753 _factory = lambda self, path, factory=None: mailbox.MH(path, factory)
754
755 def test_list_folders(self):
756 # List folders
757 self._box.add_folder('one')
758 self._box.add_folder('two')
759 self._box.add_folder('three')
760 self.assert_(len(self._box.list_folders()) == 3)
761 self.assert_(set(self._box.list_folders()) ==
762 set(('one', 'two', 'three')))
763
764 def test_get_folder(self):
765 # Open folders
766 self._box.add_folder('foo.bar')
767 folder0 = self._box.get_folder('foo.bar')
768 folder0.add(self._template % 'bar')
769 self.assert_(os.path.isdir(os.path.join(self._path, 'foo.bar')))
770 folder1 = self._box.get_folder('foo.bar')
771 self.assert_(folder1.get_string(folder1.keys()[0]) == \
772 self._template % 'bar')
773
774 def test_add_and_remove_folders(self):
775 # Delete folders
776 self._box.add_folder('one')
777 self._box.add_folder('two')
778 self.assert_(len(self._box.list_folders()) == 2)
779 self.assert_(set(self._box.list_folders()) == set(('one', 'two')))
780 self._box.remove_folder('one')
781 self.assert_(len(self._box.list_folders()) == 1)
782 self.assert_(set(self._box.list_folders()) == set(('two',)))
783 self._box.add_folder('three')
784 self.assert_(len(self._box.list_folders()) == 2)
785 self.assert_(set(self._box.list_folders()) == set(('two', 'three')))
786 self._box.remove_folder('three')
787 self.assert_(len(self._box.list_folders()) == 1)
788 self.assert_(set(self._box.list_folders()) == set(('two',)))
789 self._box.remove_folder('two')
790 self.assert_(len(self._box.list_folders()) == 0)
791 self.assert_(self._box.list_folders() == [])
792
793 def test_sequences(self):
794 # Get and set sequences
795 self.assert_(self._box.get_sequences() == {})
796 msg0 = mailbox.MHMessage(self._template % 0)
797 msg0.add_sequence('foo')
798 key0 = self._box.add(msg0)
799 self.assert_(self._box.get_sequences() == {'foo':[key0]})
800 msg1 = mailbox.MHMessage(self._template % 1)
801 msg1.set_sequences(['bar', 'replied', 'foo'])
802 key1 = self._box.add(msg1)
803 self.assert_(self._box.get_sequences() ==
804 {'foo':[key0, key1], 'bar':[key1], 'replied':[key1]})
805 msg0.set_sequences(['flagged'])
806 self._box[key0] = msg0
807 self.assert_(self._box.get_sequences() ==
808 {'foo':[key1], 'bar':[key1], 'replied':[key1],
809 'flagged':[key0]})
810 self._box.remove(key1)
811 self.assert_(self._box.get_sequences() == {'flagged':[key0]})
812
813 def test_pack(self):
814 # Pack the contents of the mailbox
815 msg0 = mailbox.MHMessage(self._template % 0)
816 msg1 = mailbox.MHMessage(self._template % 1)
817 msg2 = mailbox.MHMessage(self._template % 2)
818 msg3 = mailbox.MHMessage(self._template % 3)
819 msg0.set_sequences(['foo', 'unseen'])
820 msg1.set_sequences(['foo'])
821 msg2.set_sequences(['foo', 'flagged'])
822 msg3.set_sequences(['foo', 'bar', 'replied'])
823 key0 = self._box.add(msg0)
824 key1 = self._box.add(msg1)
825 key2 = self._box.add(msg2)
826 key3 = self._box.add(msg3)
827 self.assert_(self._box.get_sequences() ==
828 {'foo':[key0,key1,key2,key3], 'unseen':[key0],
829 'flagged':[key2], 'bar':[key3], 'replied':[key3]})
830 self._box.remove(key2)
831 self.assert_(self._box.get_sequences() ==
832 {'foo':[key0,key1,key3], 'unseen':[key0], 'bar':[key3],
833 'replied':[key3]})
834 self._box.pack()
835 self.assert_(self._box.keys() == [1, 2, 3])
836 key0 = key0
837 key1 = key0 + 1
838 key2 = key1 + 1
839 self.assert_(self._box.get_sequences() ==
840 {'foo':[1, 2, 3], 'unseen':[1], 'bar':[3], 'replied':[3]})
841
842 def _get_lock_path(self):
843 return os.path.join(self._path, '.mh_sequences.lock')
844
845
846class TestBabyl(TestMailbox):
847
848 _factory = lambda self, path, factory=None: mailbox.Babyl(path, factory)
849
850 def tearDown(self):
851 self._box.close()
852 self._delete_recursively(self._path)
853 for lock_remnant in glob.glob(self._path + '.*'):
854 os.remove(lock_remnant)
855
856 def test_labels(self):
857 # Get labels from the mailbox
858 self.assert_(self._box.get_labels() == [])
859 msg0 = mailbox.BabylMessage(self._template % 0)
860 msg0.add_label('foo')
861 key0 = self._box.add(msg0)
862 self.assert_(self._box.get_labels() == ['foo'])
863 msg1 = mailbox.BabylMessage(self._template % 1)
864 msg1.set_labels(['bar', 'answered', 'foo'])
865 key1 = self._box.add(msg1)
866 self.assert_(set(self._box.get_labels()) == set(['foo', 'bar']))
867 msg0.set_labels(['blah', 'filed'])
868 self._box[key0] = msg0
869 self.assert_(set(self._box.get_labels()) ==
870 set(['foo', 'bar', 'blah']))
871 self._box.remove(key1)
872 self.assert_(set(self._box.get_labels()) == set(['blah']))
873
874
875class TestMessage(TestBase):
876
877 _factory = mailbox.Message # Overridden by subclasses to reuse tests
878
879 def setUp(self):
880 self._path = test_support.TESTFN
881
882 def tearDown(self):
883 self._delete_recursively(self._path)
884
885 def test_initialize_with_eMM(self):
886 # Initialize based on email.Message.Message instance
887 eMM = email.message_from_string(_sample_message)
888 msg = self._factory(eMM)
889 self._post_initialize_hook(msg)
890 self._check_sample(msg)
891
892 def test_initialize_with_string(self):
893 # Initialize based on string
894 msg = self._factory(_sample_message)
895 self._post_initialize_hook(msg)
896 self._check_sample(msg)
897
898 def test_initialize_with_file(self):
899 # Initialize based on contents of file
900 f = open(self._path, 'w+')
901 f.write(_sample_message)
902 f.seek(0)
903 msg = self._factory(f)
904 self._post_initialize_hook(msg)
905 self._check_sample(msg)
906 f.close()
907
908 def test_initialize_with_nothing(self):
909 # Initialize without arguments
910 msg = self._factory()
911 self._post_initialize_hook(msg)
912 self.assert_(isinstance(msg, email.Message.Message))
913 self.assert_(isinstance(msg, mailbox.Message))
914 self.assert_(isinstance(msg, self._factory))
915 self.assert_(msg.keys() == [])
916 self.assert_(not msg.is_multipart())
917 self.assert_(msg.get_payload() == None)
918
919 def test_initialize_incorrectly(self):
920 # Initialize with invalid argument
921 self.assertRaises(TypeError, lambda: self._factory(object()))
922
923 def test_become_message(self):
924 # Take on the state of another message
925 eMM = email.message_from_string(_sample_message)
926 msg = self._factory()
927 msg._become_message(eMM)
928 self._check_sample(msg)
929
930 def test_explain_to(self):
931 # Copy self's format-specific data to other message formats.
932 # This test is superficial; better ones are in TestMessageConversion.
933 msg = self._factory()
934 for class_ in (mailbox.Message, mailbox.MaildirMessage,
935 mailbox.mboxMessage, mailbox.MHMessage,
936 mailbox.BabylMessage, mailbox.MMDFMessage):
937 other_msg = class_()
938 msg._explain_to(other_msg)
939 other_msg = email.Message.Message()
940 self.assertRaises(TypeError, lambda: msg._explain_to(other_msg))
941
942 def _post_initialize_hook(self, msg):
943 # Overridden by subclasses to check extra things after initialization
944 pass
945
946
947class TestMaildirMessage(TestMessage):
948
949 _factory = mailbox.MaildirMessage
950
951 def _post_initialize_hook(self, msg):
952 self.assert_(msg._subdir == 'new')
953 self.assert_(msg._info == '')
954
955 def test_subdir(self):
956 # Use get_subdir() and set_subdir()
957 msg = mailbox.MaildirMessage(_sample_message)
958 self.assert_(msg.get_subdir() == 'new')
959 msg.set_subdir('cur')
960 self.assert_(msg.get_subdir() == 'cur')
961 msg.set_subdir('new')
962 self.assert_(msg.get_subdir() == 'new')
963 self.assertRaises(ValueError, lambda: msg.set_subdir('tmp'))
964 self.assert_(msg.get_subdir() == 'new')
965 msg.set_subdir('new')
966 self.assert_(msg.get_subdir() == 'new')
967 self._check_sample(msg)
968
969 def test_flags(self):
970 # Use get_flags(), set_flags(), add_flag(), remove_flag()
971 msg = mailbox.MaildirMessage(_sample_message)
972 self.assert_(msg.get_flags() == '')
973 self.assert_(msg.get_subdir() == 'new')
974 msg.set_flags('F')
975 self.assert_(msg.get_subdir() == 'new')
976 self.assert_(msg.get_flags() == 'F')
977 msg.set_flags('SDTP')
978 self.assert_(msg.get_flags() == 'DPST')
979 msg.add_flag('FT')
980 self.assert_(msg.get_flags() == 'DFPST')
981 msg.remove_flag('TDRP')
982 self.assert_(msg.get_flags() == 'FS')
983 self.assert_(msg.get_subdir() == 'new')
984 self._check_sample(msg)
985
986 def test_date(self):
987 # Use get_date() and set_date()
988 msg = mailbox.MaildirMessage(_sample_message)
989 self.assert_(abs(msg.get_date() - time.time()) < 60)
990 msg.set_date(0.0)
991 self.assert_(msg.get_date() == 0.0)
992
993 def test_info(self):
994 # Use get_info() and set_info()
995 msg = mailbox.MaildirMessage(_sample_message)
996 self.assert_(msg.get_info() == '')
997 msg.set_info('1,foo=bar')
998 self.assert_(msg.get_info() == '1,foo=bar')
999 self.assertRaises(TypeError, lambda: msg.set_info(None))
1000 self._check_sample(msg)
1001
1002 def test_info_and_flags(self):
1003 # Test interaction of info and flag methods
1004 msg = mailbox.MaildirMessage(_sample_message)
1005 self.assert_(msg.get_info() == '')
1006 msg.set_flags('SF')
1007 self.assert_(msg.get_flags() == 'FS')
1008 self.assert_(msg.get_info() == '2,FS')
1009 msg.set_info('1,')
1010 self.assert_(msg.get_flags() == '')
1011 self.assert_(msg.get_info() == '1,')
1012 msg.remove_flag('RPT')
1013 self.assert_(msg.get_flags() == '')
1014 self.assert_(msg.get_info() == '1,')
1015 msg.add_flag('D')
1016 self.assert_(msg.get_flags() == 'D')
1017 self.assert_(msg.get_info() == '2,D')
1018 self._check_sample(msg)
1019
1020
1021class _TestMboxMMDFMessage(TestMessage):
1022
1023 _factory = mailbox._mboxMMDFMessage
1024
1025 def _post_initialize_hook(self, msg):
1026 self._check_from(msg)
1027
1028 def test_initialize_with_unixfrom(self):
1029 # Initialize with a message that already has a _unixfrom attribute
1030 msg = mailbox.Message(_sample_message)
1031 msg.set_unixfrom('From foo@bar blah')
1032 msg = mailbox.mboxMessage(msg)
1033 self.assert_(msg.get_from() == 'foo@bar blah', msg.get_from())
1034
1035 def test_from(self):
1036 # Get and set "From " line
1037 msg = mailbox.mboxMessage(_sample_message)
1038 self._check_from(msg)
1039 msg.set_from('foo bar')
1040 self.assert_(msg.get_from() == 'foo bar')
1041 msg.set_from('foo@bar', True)
1042 self._check_from(msg, 'foo@bar')
1043 msg.set_from('blah@temp', time.localtime())
1044 self._check_from(msg, 'blah@temp')
1045
1046 def test_flags(self):
1047 # Use get_flags(), set_flags(), add_flag(), remove_flag()
1048 msg = mailbox.mboxMessage(_sample_message)
1049 self.assert_(msg.get_flags() == '')
1050 msg.set_flags('F')
1051 self.assert_(msg.get_flags() == 'F')
1052 msg.set_flags('XODR')
1053 self.assert_(msg.get_flags() == 'RODX')
1054 msg.add_flag('FA')
1055 self.assert_(msg.get_flags() == 'RODFAX')
1056 msg.remove_flag('FDXA')
1057 self.assert_(msg.get_flags() == 'RO')
1058 self._check_sample(msg)
1059
1060 def _check_from(self, msg, sender=None):
1061 # Check contents of "From " line
1062 if sender is None:
1063 sender = "MAILER-DAEMON"
1064 self.assert_(re.match(sender + r" \w{3} \w{3} [\d ]\d [\d ]\d:\d{2}:"
1065 r"\d{2} \d{4}", msg.get_from()) is not None)
1066
1067
1068class TestMboxMessage(_TestMboxMMDFMessage):
1069
1070 _factory = mailbox.mboxMessage
1071
1072
1073class TestMHMessage(TestMessage):
1074
1075 _factory = mailbox.MHMessage
1076
1077 def _post_initialize_hook(self, msg):
1078 self.assert_(msg._sequences == [])
1079
1080 def test_sequences(self):
1081 # Get, set, join, and leave sequences
1082 msg = mailbox.MHMessage(_sample_message)
1083 self.assert_(msg.get_sequences() == [])
1084 msg.set_sequences(['foobar'])
1085 self.assert_(msg.get_sequences() == ['foobar'])
1086 msg.set_sequences([])
1087 self.assert_(msg.get_sequences() == [])
1088 msg.add_sequence('unseen')
1089 self.assert_(msg.get_sequences() == ['unseen'])
1090 msg.add_sequence('flagged')
1091 self.assert_(msg.get_sequences() == ['unseen', 'flagged'])
1092 msg.add_sequence('flagged')
1093 self.assert_(msg.get_sequences() == ['unseen', 'flagged'])
1094 msg.remove_sequence('unseen')
1095 self.assert_(msg.get_sequences() == ['flagged'])
1096 msg.add_sequence('foobar')
1097 self.assert_(msg.get_sequences() == ['flagged', 'foobar'])
1098 msg.remove_sequence('replied')
1099 self.assert_(msg.get_sequences() == ['flagged', 'foobar'])
1100 msg.set_sequences(['foobar', 'replied'])
1101 self.assert_(msg.get_sequences() == ['foobar', 'replied'])
1102
1103
1104class TestBabylMessage(TestMessage):
1105
1106 _factory = mailbox.BabylMessage
1107
1108 def _post_initialize_hook(self, msg):
1109 self.assert_(msg._labels == [])
1110
1111 def test_labels(self):
1112 # Get, set, join, and leave labels
1113 msg = mailbox.BabylMessage(_sample_message)
1114 self.assert_(msg.get_labels() == [])
1115 msg.set_labels(['foobar'])
1116 self.assert_(msg.get_labels() == ['foobar'])
1117 msg.set_labels([])
1118 self.assert_(msg.get_labels() == [])
1119 msg.add_label('filed')
1120 self.assert_(msg.get_labels() == ['filed'])
1121 msg.add_label('resent')
1122 self.assert_(msg.get_labels() == ['filed', 'resent'])
1123 msg.add_label('resent')
1124 self.assert_(msg.get_labels() == ['filed', 'resent'])
1125 msg.remove_label('filed')
1126 self.assert_(msg.get_labels() == ['resent'])
1127 msg.add_label('foobar')
1128 self.assert_(msg.get_labels() == ['resent', 'foobar'])
1129 msg.remove_label('unseen')
1130 self.assert_(msg.get_labels() == ['resent', 'foobar'])
1131 msg.set_labels(['foobar', 'answered'])
1132 self.assert_(msg.get_labels() == ['foobar', 'answered'])
1133
1134 def test_visible(self):
1135 # Get, set, and update visible headers
1136 msg = mailbox.BabylMessage(_sample_message)
1137 visible = msg.get_visible()
1138 self.assert_(visible.keys() == [])
1139 self.assert_(visible.get_payload() is None)
1140 visible['User-Agent'] = 'FooBar 1.0'
1141 visible['X-Whatever'] = 'Blah'
1142 self.assert_(msg.get_visible().keys() == [])
1143 msg.set_visible(visible)
1144 visible = msg.get_visible()
1145 self.assert_(visible.keys() == ['User-Agent', 'X-Whatever'])
1146 self.assert_(visible['User-Agent'] == 'FooBar 1.0')
1147 self.assert_(visible['X-Whatever'] == 'Blah')
1148 self.assert_(visible.get_payload() is None)
1149 msg.update_visible()
1150 self.assert_(visible.keys() == ['User-Agent', 'X-Whatever'])
1151 self.assert_(visible.get_payload() is None)
1152 visible = msg.get_visible()
1153 self.assert_(visible.keys() == ['User-Agent', 'Date', 'From', 'To',
1154 'Subject'])
1155 for header in ('User-Agent', 'Date', 'From', 'To', 'Subject'):
1156 self.assert_(visible[header] == msg[header])
1157
1158
1159class TestMMDFMessage(_TestMboxMMDFMessage):
1160
1161 _factory = mailbox.MMDFMessage
1162
1163
1164class TestMessageConversion(TestBase):
1165
1166 def test_plain_to_x(self):
1167 # Convert Message to all formats
1168 for class_ in (mailbox.Message, mailbox.MaildirMessage,
1169 mailbox.mboxMessage, mailbox.MHMessage,
1170 mailbox.BabylMessage, mailbox.MMDFMessage):
1171 msg_plain = mailbox.Message(_sample_message)
1172 msg = class_(msg_plain)
1173 self._check_sample(msg)
1174
1175 def test_x_to_plain(self):
1176 # Convert all formats to Message
1177 for class_ in (mailbox.Message, mailbox.MaildirMessage,
1178 mailbox.mboxMessage, mailbox.MHMessage,
1179 mailbox.BabylMessage, mailbox.MMDFMessage):
1180 msg = class_(_sample_message)
1181 msg_plain = mailbox.Message(msg)
1182 self._check_sample(msg_plain)
1183
1184 def test_x_to_invalid(self):
1185 # Convert all formats to an invalid format
1186 for class_ in (mailbox.Message, mailbox.MaildirMessage,
1187 mailbox.mboxMessage, mailbox.MHMessage,
1188 mailbox.BabylMessage, mailbox.MMDFMessage):
1189 self.assertRaises(TypeError, lambda: class_(False))
1190
1191 def test_maildir_to_maildir(self):
1192 # Convert MaildirMessage to MaildirMessage
1193 msg_maildir = mailbox.MaildirMessage(_sample_message)
1194 msg_maildir.set_flags('DFPRST')
1195 msg_maildir.set_subdir('cur')
1196 date = msg_maildir.get_date()
1197 msg = mailbox.MaildirMessage(msg_maildir)
1198 self._check_sample(msg)
1199 self.assert_(msg.get_flags() == 'DFPRST')
1200 self.assert_(msg.get_subdir() == 'cur')
1201 self.assert_(msg.get_date() == date)
1202
1203 def test_maildir_to_mboxmmdf(self):
1204 # Convert MaildirMessage to mboxmessage and MMDFMessage
1205 pairs = (('D', ''), ('F', 'F'), ('P', ''), ('R', 'A'), ('S', 'R'),
1206 ('T', 'D'), ('DFPRST', 'RDFA'))
1207 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1208 msg_maildir = mailbox.MaildirMessage(_sample_message)
1209 msg_maildir.set_date(0.0)
1210 for setting, result in pairs:
1211 msg_maildir.set_flags(setting)
1212 msg = class_(msg_maildir)
1213 self.assert_(msg.get_flags() == result)
1214 self.assert_(msg.get_from() == 'MAILER-DAEMON %s' %
1215 time.asctime(time.gmtime(0.0)))
1216 msg_maildir.set_subdir('cur')
1217 self.assert_(class_(msg_maildir).get_flags() == 'RODFA')
1218
1219 def test_maildir_to_mh(self):
1220 # Convert MaildirMessage to MHMessage
1221 msg_maildir = mailbox.MaildirMessage(_sample_message)
1222 pairs = (('D', ['unseen']), ('F', ['unseen', 'flagged']),
1223 ('P', ['unseen']), ('R', ['unseen', 'replied']), ('S', []),
1224 ('T', ['unseen']), ('DFPRST', ['replied', 'flagged']))
1225 for setting, result in pairs:
1226 msg_maildir.set_flags(setting)
1227 self.assert_(mailbox.MHMessage(msg_maildir).get_sequences() == \
1228 result)
1229
1230 def test_maildir_to_babyl(self):
1231 # Convert MaildirMessage to Babyl
1232 msg_maildir = mailbox.MaildirMessage(_sample_message)
1233 pairs = (('D', ['unseen']), ('F', ['unseen']),
1234 ('P', ['unseen', 'forwarded']), ('R', ['unseen', 'answered']),
1235 ('S', []), ('T', ['unseen', 'deleted']),
1236 ('DFPRST', ['deleted', 'answered', 'forwarded']))
1237 for setting, result in pairs:
1238 msg_maildir.set_flags(setting)
1239 self.assert_(mailbox.BabylMessage(msg_maildir).get_labels() == \
1240 result)
1241
1242 def test_mboxmmdf_to_maildir(self):
1243 # Convert mboxMessage and MMDFMessage to MaildirMessage
1244 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1245 msg_mboxMMDF = class_(_sample_message)
1246 msg_mboxMMDF.set_from('foo@bar', time.gmtime(0.0))
1247 pairs = (('R', 'S'), ('O', ''), ('D', 'T'), ('F', 'F'), ('A', 'R'),
1248 ('RODFA', 'FRST'))
1249 for setting, result in pairs:
1250 msg_mboxMMDF.set_flags(setting)
1251 msg = mailbox.MaildirMessage(msg_mboxMMDF)
1252 self.assert_(msg.get_flags() == result)
1253 self.assert_(msg.get_date() == 0.0, msg.get_date())
1254 msg_mboxMMDF.set_flags('O')
1255 self.assert_(mailbox.MaildirMessage(msg_mboxMMDF).get_subdir() == \
1256 'cur')
1257
1258 def test_mboxmmdf_to_mboxmmdf(self):
1259 # Convert mboxMessage and MMDFMessage to mboxMessage and MMDFMessage
1260 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1261 msg_mboxMMDF = class_(_sample_message)
1262 msg_mboxMMDF.set_flags('RODFA')
1263 msg_mboxMMDF.set_from('foo@bar')
1264 for class2_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1265 msg2 = class2_(msg_mboxMMDF)
1266 self.assert_(msg2.get_flags() == 'RODFA')
1267 self.assert_(msg2.get_from() == 'foo@bar')
1268
1269 def test_mboxmmdf_to_mh(self):
1270 # Convert mboxMessage and MMDFMessage to MHMessage
1271 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1272 msg_mboxMMDF = class_(_sample_message)
1273 pairs = (('R', []), ('O', ['unseen']), ('D', ['unseen']),
1274 ('F', ['unseen', 'flagged']),
1275 ('A', ['unseen', 'replied']),
1276 ('RODFA', ['replied', 'flagged']))
1277 for setting, result in pairs:
1278 msg_mboxMMDF.set_flags(setting)
1279 self.assert_(mailbox.MHMessage(msg_mboxMMDF).get_sequences() \
1280 == result)
1281
1282 def test_mboxmmdf_to_babyl(self):
1283 # Convert mboxMessage and MMDFMessage to BabylMessage
1284 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1285 msg = class_(_sample_message)
1286 pairs = (('R', []), ('O', ['unseen']),
1287 ('D', ['unseen', 'deleted']), ('F', ['unseen']),
1288 ('A', ['unseen', 'answered']),
1289 ('RODFA', ['deleted', 'answered']))
1290 for setting, result in pairs:
1291 msg.set_flags(setting)
1292 self.assert_(mailbox.BabylMessage(msg).get_labels() == result)
1293
1294 def test_mh_to_maildir(self):
1295 # Convert MHMessage to MaildirMessage
1296 pairs = (('unseen', ''), ('replied', 'RS'), ('flagged', 'FS'))
1297 for setting, result in pairs:
1298 msg = mailbox.MHMessage(_sample_message)
1299 msg.add_sequence(setting)
1300 self.assert_(mailbox.MaildirMessage(msg).get_flags() == result)
1301 self.assert_(mailbox.MaildirMessage(msg).get_subdir() == 'cur')
1302 msg = mailbox.MHMessage(_sample_message)
1303 msg.add_sequence('unseen')
1304 msg.add_sequence('replied')
1305 msg.add_sequence('flagged')
1306 self.assert_(mailbox.MaildirMessage(msg).get_flags() == 'FR')
1307 self.assert_(mailbox.MaildirMessage(msg).get_subdir() == 'cur')
1308
1309 def test_mh_to_mboxmmdf(self):
1310 # Convert MHMessage to mboxMessage and MMDFMessage
1311 pairs = (('unseen', 'O'), ('replied', 'ROA'), ('flagged', 'ROF'))
1312 for setting, result in pairs:
1313 msg = mailbox.MHMessage(_sample_message)
1314 msg.add_sequence(setting)
1315 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1316 self.assert_(class_(msg).get_flags() == result)
1317 msg = mailbox.MHMessage(_sample_message)
1318 msg.add_sequence('unseen')
1319 msg.add_sequence('replied')
1320 msg.add_sequence('flagged')
1321 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1322 self.assert_(class_(msg).get_flags() == 'OFA')
1323
1324 def test_mh_to_mh(self):
1325 # Convert MHMessage to MHMessage
1326 msg = mailbox.MHMessage(_sample_message)
1327 msg.add_sequence('unseen')
1328 msg.add_sequence('replied')
1329 msg.add_sequence('flagged')
1330 self.assert_(mailbox.MHMessage(msg).get_sequences() == \
1331 ['unseen', 'replied', 'flagged'])
1332
1333 def test_mh_to_babyl(self):
1334 # Convert MHMessage to BabylMessage
1335 pairs = (('unseen', ['unseen']), ('replied', ['answered']),
1336 ('flagged', []))
1337 for setting, result in pairs:
1338 msg = mailbox.MHMessage(_sample_message)
1339 msg.add_sequence(setting)
1340 self.assert_(mailbox.BabylMessage(msg).get_labels() == result)
1341 msg = mailbox.MHMessage(_sample_message)
1342 msg.add_sequence('unseen')
1343 msg.add_sequence('replied')
1344 msg.add_sequence('flagged')
1345 self.assert_(mailbox.BabylMessage(msg).get_labels() == \
1346 ['unseen', 'answered'])
1347
1348 def test_babyl_to_maildir(self):
1349 # Convert BabylMessage to MaildirMessage
1350 pairs = (('unseen', ''), ('deleted', 'ST'), ('filed', 'S'),
1351 ('answered', 'RS'), ('forwarded', 'PS'), ('edited', 'S'),
1352 ('resent', 'PS'))
1353 for setting, result in pairs:
1354 msg = mailbox.BabylMessage(_sample_message)
1355 msg.add_label(setting)
1356 self.assert_(mailbox.MaildirMessage(msg).get_flags() == result)
1357 self.assert_(mailbox.MaildirMessage(msg).get_subdir() == 'cur')
1358 msg = mailbox.BabylMessage(_sample_message)
1359 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1360 'edited', 'resent'):
1361 msg.add_label(label)
1362 self.assert_(mailbox.MaildirMessage(msg).get_flags() == 'PRT')
1363 self.assert_(mailbox.MaildirMessage(msg).get_subdir() == 'cur')
1364
1365 def test_babyl_to_mboxmmdf(self):
1366 # Convert BabylMessage to mboxMessage and MMDFMessage
1367 pairs = (('unseen', 'O'), ('deleted', 'ROD'), ('filed', 'RO'),
1368 ('answered', 'ROA'), ('forwarded', 'RO'), ('edited', 'RO'),
1369 ('resent', 'RO'))
1370 for setting, result in pairs:
1371 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1372 msg = mailbox.BabylMessage(_sample_message)
1373 msg.add_label(setting)
1374 self.assert_(class_(msg).get_flags() == result)
1375 msg = mailbox.BabylMessage(_sample_message)
1376 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1377 'edited', 'resent'):
1378 msg.add_label(label)
1379 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1380 self.assert_(class_(msg).get_flags() == 'ODA')
1381
1382 def test_babyl_to_mh(self):
1383 # Convert BabylMessage to MHMessage
1384 pairs = (('unseen', ['unseen']), ('deleted', []), ('filed', []),
1385 ('answered', ['replied']), ('forwarded', []), ('edited', []),
1386 ('resent', []))
1387 for setting, result in pairs:
1388 msg = mailbox.BabylMessage(_sample_message)
1389 msg.add_label(setting)
1390 self.assert_(mailbox.MHMessage(msg).get_sequences() == result)
1391 msg = mailbox.BabylMessage(_sample_message)
1392 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1393 'edited', 'resent'):
1394 msg.add_label(label)
1395 self.assert_(mailbox.MHMessage(msg).get_sequences() == \
1396 ['unseen', 'replied'])
1397
1398 def test_babyl_to_babyl(self):
1399 # Convert BabylMessage to BabylMessage
1400 msg = mailbox.BabylMessage(_sample_message)
1401 msg.update_visible()
1402 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1403 'edited', 'resent'):
1404 msg.add_label(label)
1405 msg2 = mailbox.BabylMessage(msg)
1406 self.assert_(msg2.get_labels() == ['unseen', 'deleted', 'filed',
1407 'answered', 'forwarded', 'edited',
1408 'resent'])
1409 self.assert_(msg.get_visible().keys() == msg2.get_visible().keys())
1410 for key in msg.get_visible().keys():
1411 self.assert_(msg.get_visible()[key] == msg2.get_visible()[key])
1412
1413
1414class TestProxyFileBase(TestBase):
1415
1416 def _test_read(self, proxy):
1417 # Read by byte
1418 proxy.seek(0)
1419 self.assert_(proxy.read() == 'bar')
1420 proxy.seek(1)
1421 self.assert_(proxy.read() == 'ar')
1422 proxy.seek(0)
1423 self.assert_(proxy.read(2) == 'ba')
1424 proxy.seek(1)
1425 self.assert_(proxy.read(-1) == 'ar')
1426 proxy.seek(2)
1427 self.assert_(proxy.read(1000) == 'r')
1428
1429 def _test_readline(self, proxy):
1430 # Read by line
1431 proxy.seek(0)
1432 self.assert_(proxy.readline() == 'foo' + os.linesep)
1433 self.assert_(proxy.readline() == 'bar' + os.linesep)
1434 self.assert_(proxy.readline() == 'fred' + os.linesep)
1435 self.assert_(proxy.readline() == 'bob')
1436 proxy.seek(2)
1437 self.assert_(proxy.readline() == 'o' + os.linesep)
1438 proxy.seek(6 + 2 * len(os.linesep))
1439 self.assert_(proxy.readline() == 'fred' + os.linesep)
1440 proxy.seek(6 + 2 * len(os.linesep))
1441 self.assert_(proxy.readline(2) == 'fr')
1442 self.assert_(proxy.readline(-10) == 'ed' + os.linesep)
1443
1444 def _test_readlines(self, proxy):
1445 # Read multiple lines
1446 proxy.seek(0)
1447 self.assert_(proxy.readlines() == ['foo' + os.linesep,
1448 'bar' + os.linesep,
1449 'fred' + os.linesep, 'bob'])
1450 proxy.seek(0)
1451 self.assert_(proxy.readlines(2) == ['foo' + os.linesep])
1452 proxy.seek(3 + len(os.linesep))
1453 self.assert_(proxy.readlines(4 + len(os.linesep)) ==
1454 ['bar' + os.linesep, 'fred' + os.linesep])
1455 proxy.seek(3)
1456 self.assert_(proxy.readlines(1000) == [os.linesep, 'bar' + os.linesep,
1457 'fred' + os.linesep, 'bob'])
1458
1459 def _test_iteration(self, proxy):
1460 # Iterate by line
1461 proxy.seek(0)
1462 iterator = iter(proxy)
1463 self.assert_(iterator.next() == 'foo' + os.linesep)
1464 self.assert_(iterator.next() == 'bar' + os.linesep)
1465 self.assert_(iterator.next() == 'fred' + os.linesep)
1466 self.assert_(iterator.next() == 'bob')
1467 self.assertRaises(StopIteration, lambda: iterator.next())
1468
1469 def _test_seek_and_tell(self, proxy):
1470 # Seek and use tell to check position
1471 proxy.seek(3)
1472 self.assert_(proxy.tell() == 3)
1473 self.assert_(proxy.read(len(os.linesep)) == os.linesep)
1474 proxy.seek(2, 1)
1475 self.assert_(proxy.read(1 + len(os.linesep)) == 'r' + os.linesep)
1476 proxy.seek(-3 - len(os.linesep), 2)
1477 self.assert_(proxy.read(3) == 'bar')
1478 proxy.seek(2, 0)
1479 self.assert_(proxy.read() == 'o' + os.linesep + 'bar' + os.linesep)
1480 proxy.seek(100)
1481 self.assert_(proxy.read() == '')
1482
1483 def _test_close(self, proxy):
1484 # Close a file
1485 proxy.close()
1486 self.assertRaises(AttributeError, lambda: proxy.close())
1487
1488
1489class TestProxyFile(TestProxyFileBase):
1490
1491 def setUp(self):
1492 self._path = test_support.TESTFN
1493 self._file = open(self._path, 'wb+')
1494
1495 def tearDown(self):
1496 self._file.close()
1497 self._delete_recursively(self._path)
1498
1499 def test_initialize(self):
1500 # Initialize and check position
1501 self._file.write('foo')
1502 pos = self._file.tell()
1503 proxy0 = mailbox._ProxyFile(self._file)
1504 self.assert_(proxy0.tell() == pos)
1505 self.assert_(self._file.tell() == pos)
1506 proxy1 = mailbox._ProxyFile(self._file, 0)
1507 self.assert_(proxy1.tell() == 0)
1508 self.assert_(self._file.tell() == pos)
1509
1510 def test_read(self):
1511 self._file.write('bar')
1512 self._test_read(mailbox._ProxyFile(self._file))
1513
1514 def test_readline(self):
1515 self._file.write('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
1516 os.linesep))
1517 self._test_readline(mailbox._ProxyFile(self._file))
1518
1519 def test_readlines(self):
1520 self._file.write('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
1521 os.linesep))
1522 self._test_readlines(mailbox._ProxyFile(self._file))
1523
1524 def test_iteration(self):
1525 self._file.write('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
1526 os.linesep))
1527 self._test_iteration(mailbox._ProxyFile(self._file))
1528
1529 def test_seek_and_tell(self):
1530 self._file.write('foo%sbar%s' % (os.linesep, os.linesep))
1531 self._test_seek_and_tell(mailbox._ProxyFile(self._file))
1532
1533 def test_close(self):
1534 self._file.write('foo%sbar%s' % (os.linesep, os.linesep))
1535 self._test_close(mailbox._ProxyFile(self._file))
1536
1537
1538class TestPartialFile(TestProxyFileBase):
1539
1540 def setUp(self):
1541 self._path = test_support.TESTFN
1542 self._file = open(self._path, 'wb+')
1543
1544 def tearDown(self):
1545 self._file.close()
1546 self._delete_recursively(self._path)
1547
1548 def test_initialize(self):
1549 # Initialize and check position
1550 self._file.write('foo' + os.linesep + 'bar')
1551 pos = self._file.tell()
1552 proxy = mailbox._PartialFile(self._file, 2, 5)
1553 self.assert_(proxy.tell() == 0)
1554 self.assert_(self._file.tell() == pos)
1555
1556 def test_read(self):
1557 self._file.write('***bar***')
1558 self._test_read(mailbox._PartialFile(self._file, 3, 6))
1559
1560 def test_readline(self):
1561 self._file.write('!!!!!foo%sbar%sfred%sbob!!!!!' %
1562 (os.linesep, os.linesep, os.linesep))
1563 self._test_readline(mailbox._PartialFile(self._file, 5,
1564 18 + 3 * len(os.linesep)))
1565
1566 def test_readlines(self):
1567 self._file.write('foo%sbar%sfred%sbob?????' %
1568 (os.linesep, os.linesep, os.linesep))
1569 self._test_readlines(mailbox._PartialFile(self._file, 0,
1570 13 + 3 * len(os.linesep)))
1571
1572 def test_iteration(self):
1573 self._file.write('____foo%sbar%sfred%sbob####' %
1574 (os.linesep, os.linesep, os.linesep))
1575 self._test_iteration(mailbox._PartialFile(self._file, 4,
1576 17 + 3 * len(os.linesep)))
1577
1578 def test_seek_and_tell(self):
1579 self._file.write('(((foo%sbar%s$$$' % (os.linesep, os.linesep))
1580 self._test_seek_and_tell(mailbox._PartialFile(self._file, 3,
1581 9 + 2 * len(os.linesep)))
1582
1583 def test_close(self):
1584 self._file.write('&foo%sbar%s^' % (os.linesep, os.linesep))
1585 self._test_close(mailbox._PartialFile(self._file, 1,
1586 6 + 3 * len(os.linesep)))
1587
1588
1589## Start: tests from the original module (for backward compatibility).
1590
Skip Montanaro5253da12004-07-24 19:56:03 +00001591FROM_ = "From some.body@dummy.domain Sat Jul 24 13:43:35 2004\n"
Fred Drakec02bc3e2001-05-21 20:23:21 +00001592DUMMY_MESSAGE = """\
1593From: some.body@dummy.domain
1594To: me@my.domain
Skip Montanaro5253da12004-07-24 19:56:03 +00001595Subject: Simple Test
Fred Drakec02bc3e2001-05-21 20:23:21 +00001596
1597This is a dummy message.
1598"""
1599
Fred Drakec02bc3e2001-05-21 20:23:21 +00001600class MaildirTestCase(unittest.TestCase):
1601
1602 def setUp(self):
1603 # create a new maildir mailbox to work with:
1604 self._dir = test_support.TESTFN
1605 os.mkdir(self._dir)
1606 os.mkdir(os.path.join(self._dir, "cur"))
1607 os.mkdir(os.path.join(self._dir, "tmp"))
1608 os.mkdir(os.path.join(self._dir, "new"))
1609 self._counter = 1
1610 self._msgfiles = []
1611
1612 def tearDown(self):
1613 map(os.unlink, self._msgfiles)
1614 os.rmdir(os.path.join(self._dir, "cur"))
1615 os.rmdir(os.path.join(self._dir, "tmp"))
1616 os.rmdir(os.path.join(self._dir, "new"))
1617 os.rmdir(self._dir)
1618
Skip Montanaro5253da12004-07-24 19:56:03 +00001619 def createMessage(self, dir, mbox=False):
Jack Jansen97df7b62001-06-19 20:20:05 +00001620 t = int(time.time() % 1000000)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001621 pid = self._counter
1622 self._counter += 1
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001623 filename = os.extsep.join((str(t), str(pid), "myhostname", "mydomain"))
Fred Drakec02bc3e2001-05-21 20:23:21 +00001624 tmpname = os.path.join(self._dir, "tmp", filename)
1625 newname = os.path.join(self._dir, dir, filename)
1626 fp = open(tmpname, "w")
1627 self._msgfiles.append(tmpname)
Skip Montanaro5253da12004-07-24 19:56:03 +00001628 if mbox:
1629 fp.write(FROM_)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001630 fp.write(DUMMY_MESSAGE)
1631 fp.close()
Tim Peters6626c1f2001-05-22 16:29:01 +00001632 if hasattr(os, "link"):
1633 os.link(tmpname, newname)
1634 else:
1635 fp = open(newname, "w")
1636 fp.write(DUMMY_MESSAGE)
1637 fp.close()
Fred Drakec02bc3e2001-05-21 20:23:21 +00001638 self._msgfiles.append(newname)
Skip Montanaro5253da12004-07-24 19:56:03 +00001639 return tmpname
Fred Drakec02bc3e2001-05-21 20:23:21 +00001640
1641 def test_empty_maildir(self):
1642 """Test an empty maildir mailbox"""
1643 # Test for regression on bug #117490:
1644 # Make sure the boxes attribute actually gets set.
1645 self.mbox = mailbox.Maildir(test_support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001646 #self.assert_(hasattr(self.mbox, "boxes"))
1647 #self.assert_(len(self.mbox.boxes) == 0)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001648 self.assert_(self.mbox.next() is None)
1649 self.assert_(self.mbox.next() is None)
1650
1651 def test_nonempty_maildir_cur(self):
1652 self.createMessage("cur")
1653 self.mbox = mailbox.Maildir(test_support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001654 #self.assert_(len(self.mbox.boxes) == 1)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001655 self.assert_(self.mbox.next() is not None)
1656 self.assert_(self.mbox.next() is None)
1657 self.assert_(self.mbox.next() is None)
1658
1659 def test_nonempty_maildir_new(self):
1660 self.createMessage("new")
1661 self.mbox = mailbox.Maildir(test_support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001662 #self.assert_(len(self.mbox.boxes) == 1)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001663 self.assert_(self.mbox.next() is not None)
1664 self.assert_(self.mbox.next() is None)
1665 self.assert_(self.mbox.next() is None)
1666
1667 def test_nonempty_maildir_both(self):
1668 self.createMessage("cur")
1669 self.createMessage("new")
1670 self.mbox = mailbox.Maildir(test_support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001671 #self.assert_(len(self.mbox.boxes) == 2)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001672 self.assert_(self.mbox.next() is not None)
1673 self.assert_(self.mbox.next() is not None)
1674 self.assert_(self.mbox.next() is None)
1675 self.assert_(self.mbox.next() is None)
Fred Drake0aaed272000-10-23 13:39:15 +00001676
Skip Montanaro5253da12004-07-24 19:56:03 +00001677 def test_unix_mbox(self):
1678 ### should be better!
1679 import email.Parser
1680 fname = self.createMessage("cur", True)
1681 n = 0
1682 for msg in mailbox.PortableUnixMailbox(open(fname),
1683 email.Parser.Parser().parse):
1684 n += 1
1685 self.assertEqual(msg["subject"], "Simple Test")
1686 self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE))
1687 self.assertEqual(n, 1)
1688
Thomas Wouters477c8d52006-05-27 19:21:47 +00001689## End: classes from the original module (for backward compatibility).
1690
1691
1692_sample_message = """\
1693Return-Path: <gkj@gregorykjohnson.com>
1694X-Original-To: gkj+person@localhost
1695Delivered-To: gkj+person@localhost
1696Received: from localhost (localhost [127.0.0.1])
1697 by andy.gregorykjohnson.com (Postfix) with ESMTP id 356ED9DD17
1698 for <gkj+person@localhost>; Wed, 13 Jul 2005 17:23:16 -0400 (EDT)
1699Delivered-To: gkj@sundance.gregorykjohnson.com
1700Received: from localhost [127.0.0.1]
1701 by localhost with POP3 (fetchmail-6.2.5)
1702 for gkj+person@localhost (single-drop); Wed, 13 Jul 2005 17:23:16 -0400 (EDT)
1703Received: from andy.gregorykjohnson.com (andy.gregorykjohnson.com [64.32.235.228])
1704 by sundance.gregorykjohnson.com (Postfix) with ESMTP id 5B056316746
1705 for <gkj@gregorykjohnson.com>; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)
1706Received: by andy.gregorykjohnson.com (Postfix, from userid 1000)
1707 id 490CD9DD17; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)
1708Date: Wed, 13 Jul 2005 17:23:11 -0400
1709From: "Gregory K. Johnson" <gkj@gregorykjohnson.com>
1710To: gkj@gregorykjohnson.com
1711Subject: Sample message
1712Message-ID: <20050713212311.GC4701@andy.gregorykjohnson.com>
1713Mime-Version: 1.0
1714Content-Type: multipart/mixed; boundary="NMuMz9nt05w80d4+"
1715Content-Disposition: inline
1716User-Agent: Mutt/1.5.9i
1717
1718
1719--NMuMz9nt05w80d4+
1720Content-Type: text/plain; charset=us-ascii
1721Content-Disposition: inline
1722
1723This is a sample message.
1724
1725--
1726Gregory K. Johnson
1727
1728--NMuMz9nt05w80d4+
1729Content-Type: application/octet-stream
1730Content-Disposition: attachment; filename="text.gz"
1731Content-Transfer-Encoding: base64
1732
1733H4sICM2D1UIAA3RleHQAC8nILFYAokSFktSKEoW0zJxUPa7wzJIMhZLyfIWczLzUYj0uAHTs
17343FYlAAAA
1735
1736--NMuMz9nt05w80d4+--
1737"""
1738
1739_sample_headers = {
1740 "Return-Path":"<gkj@gregorykjohnson.com>",
1741 "X-Original-To":"gkj+person@localhost",
1742 "Delivered-To":"gkj+person@localhost",
1743 "Received":"""from localhost (localhost [127.0.0.1])
1744 by andy.gregorykjohnson.com (Postfix) with ESMTP id 356ED9DD17
1745 for <gkj+person@localhost>; Wed, 13 Jul 2005 17:23:16 -0400 (EDT)""",
1746 "Delivered-To":"gkj@sundance.gregorykjohnson.com",
1747 "Received":"""from localhost [127.0.0.1]
1748 by localhost with POP3 (fetchmail-6.2.5)
1749 for gkj+person@localhost (single-drop); Wed, 13 Jul 2005 17:23:16 -0400 (EDT)""",
1750 "Received":"""from andy.gregorykjohnson.com (andy.gregorykjohnson.com [64.32.235.228])
1751 by sundance.gregorykjohnson.com (Postfix) with ESMTP id 5B056316746
1752 for <gkj@gregorykjohnson.com>; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)""",
1753 "Received":"""by andy.gregorykjohnson.com (Postfix, from userid 1000)
1754 id 490CD9DD17; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)""",
1755 "Date":"Wed, 13 Jul 2005 17:23:11 -0400",
1756 "From":""""Gregory K. Johnson" <gkj@gregorykjohnson.com>""",
1757 "To":"gkj@gregorykjohnson.com",
1758 "Subject":"Sample message",
1759 "Mime-Version":"1.0",
1760 "Content-Type":"""multipart/mixed; boundary="NMuMz9nt05w80d4+\"""",
1761 "Content-Disposition":"inline",
1762 "User-Agent": "Mutt/1.5.9i" }
1763
1764_sample_payloads = ("""This is a sample message.
1765
1766--
1767Gregory K. Johnson
1768""",
1769"""H4sICM2D1UIAA3RleHQAC8nILFYAokSFktSKEoW0zJxUPa7wzJIMhZLyfIWczLzUYj0uAHTs
17703FYlAAAA
1771""")
Fred Drake0aaed272000-10-23 13:39:15 +00001772
Fred Drakec02bc3e2001-05-21 20:23:21 +00001773
Fred Drake2e2be372001-09-20 21:33:42 +00001774def test_main():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001775 tests = (TestMailboxSuperclass, TestMaildir, TestMbox, TestMMDF, TestMH,
1776 TestBabyl, TestMessage, TestMaildirMessage, TestMboxMessage,
1777 TestMHMessage, TestBabylMessage, TestMMDFMessage,
1778 TestMessageConversion, TestProxyFile, TestPartialFile,
1779 MaildirTestCase)
1780 test_support.run_unittest(*tests)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001781 test_support.reap_children()
Fred Drake2e2be372001-09-20 21:33:42 +00001782
1783
Thomas Wouters477c8d52006-05-27 19:21:47 +00001784if __name__ == '__main__':
Fred Drake2e2be372001-09-20 21:33:42 +00001785 test_main()