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