blob: e5930d80f628967f87cc653f6401e6f7e6c7fd0a [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())
Guido van Rossume61fd5b2007-07-11 12:20:59 +000030 self.assertEqual(len(msg.get_payload()), len(_sample_payloads))
Thomas Wouters477c8d52006-05-27 19:21:47 +000031 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))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000035 self.assertEqual(part.get_payload(), payload)
Thomas Wouters477c8d52006-05-27 19:21:47 +000036
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))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000068 self.assertEqual(len(self._box), 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000069 keys.append(self._box.add(mailbox.Message(_sample_message)))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000070 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +000071 keys.append(self._box.add(email.message_from_string(_sample_message)))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000072 self.assertEqual(len(self._box), 3)
Thomas Wouters477c8d52006-05-27 19:21:47 +000073 keys.append(self._box.add(StringIO.StringIO(_sample_message)))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000074 self.assertEqual(len(self._box), 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +000075 keys.append(self._box.add(_sample_message))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000076 self.assertEqual(len(self._box), 5)
Thomas Wouters477c8d52006-05-27 19:21:47 +000077 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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +000093 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +000094 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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000101 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000102 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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000109 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000110 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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000117 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000118 self._box.discard(key0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000119 self.assertEqual(len(self._box), 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000120 self.assertRaises(KeyError, lambda: self._box[key0])
121 self._box.discard(key0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000122 self.assertEqual(len(self._box), 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000123 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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000129 self.assertEqual(msg['from'], 'foo')
130 self.assertEqual(msg.get_payload(), '0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000131 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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000137 self.assertEqual(msg['from'], 'foo')
138 self.assertEqual(msg.fp.read(), '1')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000139
140 def test_getitem(self):
141 # Retrieve message using __getitem__()
142 key0 = self._box.add(self._template % 0)
143 msg = self._box[key0]
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000144 self.assertEqual(msg['from'], 'foo')
145 self.assertEqual(msg.get_payload(), '0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000146 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))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000156 self.assertEqual(msg0['from'], 'foo')
157 self.assertEqual(msg0.get_payload(), '0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000158 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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000165 self.assertEqual(self._box.get_string(key1), _sample_message)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000166
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 = [], []
Guido van Rossum805365e2007-05-07 22:24:25 +0000211 for i in range(repetitions):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000212 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:
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000224 self.assertEqual(len(keys), len(returned_keys))
225 self.assertEqual(set(keys), set(returned_keys))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000226 if do_values:
227 count = 0
228 for value in returned_values:
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000229 self.assertEqual(value['from'], 'foo')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000230 self.assert_(int(value.get_payload()) < repetitions)
231 count += 1
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000232 self.assertEqual(len(values), count)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000233
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 = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000257 for i in range(repetitions):
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000258 self.assertEqual(len(self._box), i)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000259 keys.append(self._box.add(self._template % i))
260 self.assert_(len(self._box) == i + 1)
Guido van Rossum805365e2007-05-07 22:24:25 +0000261 for i in range(repetitions):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000262 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'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000291 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000292
293 def test_clear(self, iterations=10):
294 # Remove all messages using clear()
295 keys = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000296 for i in range(iterations):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000297 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()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000301 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000302 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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000311 self.assertEqual(self._box.pop(key0).get_payload(), '0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000312 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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000316 self.assertEqual(self._box.pop(key2).get_payload(), '2')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000317 self.assert_(key2 not in self._box)
318 self.assert_(key1 in self._box)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000319 self.assertEqual(self._box.pop(key1).get_payload(), '1')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000320 self.assert_(key1 not in self._box)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000321 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000322
323 def test_popitem(self, iterations=10):
324 # Get and remove an arbitrary (key, message) using popitem()
325 keys = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000326 for i in range(10):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000327 keys.append(self._box.add(self._template % i))
328 seen = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000329 for i in range(10):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000330 key, msg = self._box.popitem()
331 self.assert_(key in keys)
332 self.assert_(key not in seen)
333 seen.append(key)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000334 self.assertEqual(int(msg.get_payload()), keys.index(key))
335 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000336 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})
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000346 self.assertEqual(len(self._box), 3)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000347 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')])
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000355 self.assertEqual(len(self._box), 3)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000356 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"}))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000365 self.assertEqual(len(self._box), 3)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000366 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):
Guido van Rossum805365e2007-05-07 22:24:25 +0000390 contents = [self._template % i for i in range(3)]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000391 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()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000397 self.assertEqual(len(keys), 3)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000398 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())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000430 self.assertRaises(NotImplementedError, lambda: box.values().__next__())
431 self.assertRaises(NotImplementedError, lambda: box.__iter__().__next__())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000432 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))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000479 self.assertEqual(msg_returned.get_subdir(), 'cur')
480 self.assertEqual(msg_returned.get_flags(), 'FR')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000481
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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000488 self.assertEqual(msg_returned.get_subdir(), 'new')
489 self.assertEqual(msg_returned.get_flags(), 'PT')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000490 msg1 = mailbox.MaildirMessage(self._template % 1)
491 self._box[key] = msg1
492 msg_returned = self._box.get_message(key)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000493 self.assertEqual(msg_returned.get_subdir(), 'new')
494 self.assertEqual(msg_returned.get_flags(), '')
495 self.assertEqual(msg_returned.get_payload(), '1')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000496 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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000501 self.assertEqual(msg_returned.get_subdir(), 'new')
502 self.assertEqual(msg_returned.get_flags(), 'S')
503 self.assertEqual(msg_returned.get_payload(), '3')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000504
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')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000538 self.assertEqual(len(self._box.list_folders()), 3)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539 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')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000556 self.assertEqual(len(self._box.list_folders()), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000557 self.assert_(set(self._box.list_folders()) == set(('one', 'two')))
558 self._box.remove_folder('one')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000559 self.assertEqual(len(self._box.list_folders()), 1)
560 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000561 self._box.add_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000562 self.assertEqual(len(self._box.list_folders()), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000563 self.assert_(set(self._box.list_folders()) == set(('two', 'three')))
564 self._box.remove_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000565 self.assertEqual(len(self._box.list_folders()), 1)
566 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000567 self._box.remove_folder('two')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000568 self.assertEqual(len(self._box.list_folders()), 0)
569 self.assertEqual(self._box.list_folders(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +0000570
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
Guido van Rossum805365e2007-05-07 22:24:25 +0000602 for x in range(repetitions):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000603 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))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000622 self.assertEqual(int(groups[3]), int(previous_groups[3]) + 1,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000623 "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)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000631 self.assertEqual(tmp_file.read(), _sample_message)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000632 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
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000640 self.assertEqual(self._box._toc, {})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000641 key0 = self._box.add(self._template % 0)
642 key1 = self._box.add(self._template % 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000643 self.assertEqual(self._box._toc, {})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000644 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))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000663 self.assertEqual(self._box._toc, {})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000664
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
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000682 def test_directory_in_folder (self):
683 # Test that mailboxes still work if there's a stray extra directory
684 # in a folder.
685 for i in range(10):
686 self._box.add(mailbox.Message(_sample_message))
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000687
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000688 # Create a stray directory
689 os.mkdir(os.path.join(self._path, 'cur', 'stray-dir'))
690
691 # Check that looping still works with the directory present.
692 for msg in self._box:
693 pass
Thomas Wouters477c8d52006-05-27 19:21:47 +0000694
695class _TestMboxMMDF(TestMailbox):
696
697 def tearDown(self):
698 self._box.close()
699 self._delete_recursively(self._path)
700 for lock_remnant in glob.glob(self._path + '.*'):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000701 test_support.unlink(lock_remnant)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000702
703 def test_add_from_string(self):
704 # Add a string starting with 'From ' to the mailbox
705 key = self._box.add('From foo@bar blah\nFrom: foo\n\n0')
706 self.assert_(self._box[key].get_from() == 'foo@bar blah')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000707 self.assertEqual(self._box[key].get_payload(), '0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000708
709 def test_add_mbox_or_mmdf_message(self):
710 # Add an mboxMessage or MMDFMessage
711 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
712 msg = class_('From foo@bar blah\nFrom: foo\n\n0')
713 key = self._box.add(msg)
714
715 def test_open_close_open(self):
716 # Open and inspect previously-created mailbox
Guido van Rossum805365e2007-05-07 22:24:25 +0000717 values = [self._template % i for i in range(3)]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000718 for value in values:
719 self._box.add(value)
720 self._box.close()
721 mtime = os.path.getmtime(self._path)
722 self._box = self._factory(self._path)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000723 self.assertEqual(len(self._box), 3)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000724 for key in self._box.keys():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000725 self.assert_(self._box.get_string(key) in values)
726 self._box.close()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000727 self.assertEqual(mtime, os.path.getmtime(self._path))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000728
729 def test_add_and_close(self):
730 # Verifying that closing a mailbox doesn't change added items
731 self._box.add(_sample_message)
Guido van Rossum805365e2007-05-07 22:24:25 +0000732 for i in range(3):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000733 self._box.add(self._template % i)
734 self._box.add(_sample_message)
735 self._box._file.flush()
736 self._box._file.seek(0)
737 contents = self._box._file.read()
738 self._box.close()
739 self.assert_(contents == open(self._path, 'rb').read())
740 self._box = self._factory(self._path)
741
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000742 def test_lock_conflict(self):
743 # Fork off a subprocess that will lock the file for 2 seconds,
744 # unlock it, and then exit.
745 if not hasattr(os, 'fork'):
746 return
747 pid = os.fork()
748 if pid == 0:
749 # In the child, lock the mailbox.
Guido van Rossum62cbc8a2007-04-09 00:41:25 +0000750 try:
751 self._box.lock()
752 time.sleep(2)
753 self._box.unlock()
754 finally:
755 os._exit(0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000756
757 # In the parent, sleep a bit to give the child time to acquire
758 # the lock.
759 time.sleep(0.5)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000760 try:
761 self.assertRaises(mailbox.ExternalClashError,
762 self._box.lock)
763 finally:
764 # Wait for child to exit. Locking should now succeed.
765 exited_pid, status = os.waitpid(pid, 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000766
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000767 self._box.lock()
768 self._box.unlock()
769
Thomas Wouters89f507f2006-12-13 04:49:30 +0000770 def test_relock(self):
771 # Test case for bug #1575506: the mailbox class was locking the
772 # wrong file object in its flush() method.
773 msg = "Subject: sub\n\nbody\n"
774 key1 = self._box.add(msg)
775 self._box.flush()
776 self._box.close()
777
778 self._box = self._factory(self._path)
779 self._box.lock()
780 key2 = self._box.add(msg)
781 self._box.flush()
782 self.assert_(self._box._locked)
783 self._box.close()
784
785
Thomas Wouters477c8d52006-05-27 19:21:47 +0000786
787class TestMbox(_TestMboxMMDF):
788
789 _factory = lambda self, path, factory=None: mailbox.mbox(path, factory)
790
791
792class TestMMDF(_TestMboxMMDF):
793
794 _factory = lambda self, path, factory=None: mailbox.MMDF(path, factory)
795
796
797class TestMH(TestMailbox):
798
799 _factory = lambda self, path, factory=None: mailbox.MH(path, factory)
800
801 def test_list_folders(self):
802 # List folders
803 self._box.add_folder('one')
804 self._box.add_folder('two')
805 self._box.add_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000806 self.assertEqual(len(self._box.list_folders()), 3)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000807 self.assert_(set(self._box.list_folders()) ==
808 set(('one', 'two', 'three')))
809
810 def test_get_folder(self):
811 # Open folders
Thomas Wouters89f507f2006-12-13 04:49:30 +0000812 def dummy_factory (s):
813 return None
814 self._box = self._factory(self._path, dummy_factory)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000815
Thomas Wouters89f507f2006-12-13 04:49:30 +0000816 new_folder = self._box.add_folder('foo.bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000817 folder0 = self._box.get_folder('foo.bar')
818 folder0.add(self._template % 'bar')
819 self.assert_(os.path.isdir(os.path.join(self._path, 'foo.bar')))
820 folder1 = self._box.get_folder('foo.bar')
821 self.assert_(folder1.get_string(folder1.keys()[0]) == \
822 self._template % 'bar')
823
Thomas Wouters89f507f2006-12-13 04:49:30 +0000824 # Test for bug #1569790: verify that folders returned by .get_folder()
825 # use the same factory function.
826 self.assert_(new_folder._factory is self._box._factory)
827 self.assert_(folder0._factory is self._box._factory)
828
Thomas Wouters477c8d52006-05-27 19:21:47 +0000829 def test_add_and_remove_folders(self):
830 # Delete folders
831 self._box.add_folder('one')
832 self._box.add_folder('two')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000833 self.assertEqual(len(self._box.list_folders()), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000834 self.assert_(set(self._box.list_folders()) == set(('one', 'two')))
835 self._box.remove_folder('one')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000836 self.assertEqual(len(self._box.list_folders()), 1)
837 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000838 self._box.add_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000839 self.assertEqual(len(self._box.list_folders()), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000840 self.assert_(set(self._box.list_folders()) == set(('two', 'three')))
841 self._box.remove_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000842 self.assertEqual(len(self._box.list_folders()), 1)
843 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000844 self._box.remove_folder('two')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000845 self.assertEqual(len(self._box.list_folders()), 0)
846 self.assertEqual(self._box.list_folders(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +0000847
848 def test_sequences(self):
849 # Get and set sequences
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000850 self.assertEqual(self._box.get_sequences(), {})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000851 msg0 = mailbox.MHMessage(self._template % 0)
852 msg0.add_sequence('foo')
853 key0 = self._box.add(msg0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000854 self.assertEqual(self._box.get_sequences(), {'foo':[key0]})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000855 msg1 = mailbox.MHMessage(self._template % 1)
856 msg1.set_sequences(['bar', 'replied', 'foo'])
857 key1 = self._box.add(msg1)
858 self.assert_(self._box.get_sequences() ==
859 {'foo':[key0, key1], 'bar':[key1], 'replied':[key1]})
860 msg0.set_sequences(['flagged'])
861 self._box[key0] = msg0
862 self.assert_(self._box.get_sequences() ==
863 {'foo':[key1], 'bar':[key1], 'replied':[key1],
864 'flagged':[key0]})
865 self._box.remove(key1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000866 self.assertEqual(self._box.get_sequences(), {'flagged':[key0]})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000867
868 def test_pack(self):
869 # Pack the contents of the mailbox
870 msg0 = mailbox.MHMessage(self._template % 0)
871 msg1 = mailbox.MHMessage(self._template % 1)
872 msg2 = mailbox.MHMessage(self._template % 2)
873 msg3 = mailbox.MHMessage(self._template % 3)
874 msg0.set_sequences(['foo', 'unseen'])
875 msg1.set_sequences(['foo'])
876 msg2.set_sequences(['foo', 'flagged'])
877 msg3.set_sequences(['foo', 'bar', 'replied'])
878 key0 = self._box.add(msg0)
879 key1 = self._box.add(msg1)
880 key2 = self._box.add(msg2)
881 key3 = self._box.add(msg3)
882 self.assert_(self._box.get_sequences() ==
883 {'foo':[key0,key1,key2,key3], 'unseen':[key0],
884 'flagged':[key2], 'bar':[key3], 'replied':[key3]})
885 self._box.remove(key2)
886 self.assert_(self._box.get_sequences() ==
887 {'foo':[key0,key1,key3], 'unseen':[key0], 'bar':[key3],
888 'replied':[key3]})
889 self._box.pack()
890 self.assert_(self._box.keys() == [1, 2, 3])
891 key0 = key0
892 key1 = key0 + 1
893 key2 = key1 + 1
894 self.assert_(self._box.get_sequences() ==
895 {'foo':[1, 2, 3], 'unseen':[1], 'bar':[3], 'replied':[3]})
896
Thomas Wouters89f507f2006-12-13 04:49:30 +0000897 # Test case for packing while holding the mailbox locked.
898 key0 = self._box.add(msg1)
899 key1 = self._box.add(msg1)
900 key2 = self._box.add(msg1)
901 key3 = self._box.add(msg1)
902
903 self._box.remove(key0)
904 self._box.remove(key2)
905 self._box.lock()
906 self._box.pack()
907 self._box.unlock()
908 self.assert_(self._box.get_sequences() ==
909 {'foo':[1, 2, 3, 4, 5],
910 'unseen':[1], 'bar':[3], 'replied':[3]})
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000911
Thomas Wouters477c8d52006-05-27 19:21:47 +0000912 def _get_lock_path(self):
913 return os.path.join(self._path, '.mh_sequences.lock')
914
915
916class TestBabyl(TestMailbox):
917
918 _factory = lambda self, path, factory=None: mailbox.Babyl(path, factory)
919
920 def tearDown(self):
921 self._box.close()
922 self._delete_recursively(self._path)
923 for lock_remnant in glob.glob(self._path + '.*'):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000924 test_support.unlink(lock_remnant)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000925
926 def test_labels(self):
927 # Get labels from the mailbox
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000928 self.assertEqual(self._box.get_labels(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +0000929 msg0 = mailbox.BabylMessage(self._template % 0)
930 msg0.add_label('foo')
931 key0 = self._box.add(msg0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000932 self.assertEqual(self._box.get_labels(), ['foo'])
Thomas Wouters477c8d52006-05-27 19:21:47 +0000933 msg1 = mailbox.BabylMessage(self._template % 1)
934 msg1.set_labels(['bar', 'answered', 'foo'])
935 key1 = self._box.add(msg1)
936 self.assert_(set(self._box.get_labels()) == set(['foo', 'bar']))
937 msg0.set_labels(['blah', 'filed'])
938 self._box[key0] = msg0
939 self.assert_(set(self._box.get_labels()) ==
940 set(['foo', 'bar', 'blah']))
941 self._box.remove(key1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000942 self.assertEqual(set(self._box.get_labels()), set(['blah']))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000943
944
945class TestMessage(TestBase):
946
947 _factory = mailbox.Message # Overridden by subclasses to reuse tests
948
949 def setUp(self):
950 self._path = test_support.TESTFN
951
952 def tearDown(self):
953 self._delete_recursively(self._path)
954
955 def test_initialize_with_eMM(self):
Thomas Woutersb2137042007-02-01 18:02:27 +0000956 # Initialize based on email.message.Message instance
Thomas Wouters477c8d52006-05-27 19:21:47 +0000957 eMM = email.message_from_string(_sample_message)
958 msg = self._factory(eMM)
959 self._post_initialize_hook(msg)
960 self._check_sample(msg)
961
962 def test_initialize_with_string(self):
963 # Initialize based on string
964 msg = self._factory(_sample_message)
965 self._post_initialize_hook(msg)
966 self._check_sample(msg)
967
968 def test_initialize_with_file(self):
969 # Initialize based on contents of file
970 f = open(self._path, 'w+')
971 f.write(_sample_message)
972 f.seek(0)
973 msg = self._factory(f)
974 self._post_initialize_hook(msg)
975 self._check_sample(msg)
976 f.close()
977
978 def test_initialize_with_nothing(self):
979 # Initialize without arguments
980 msg = self._factory()
981 self._post_initialize_hook(msg)
Thomas Woutersb2137042007-02-01 18:02:27 +0000982 self.assert_(isinstance(msg, email.message.Message))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000983 self.assert_(isinstance(msg, mailbox.Message))
984 self.assert_(isinstance(msg, self._factory))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000985 self.assertEqual(msg.keys(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +0000986 self.assert_(not msg.is_multipart())
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000987 self.assertEqual(msg.get_payload(), None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000988
989 def test_initialize_incorrectly(self):
990 # Initialize with invalid argument
991 self.assertRaises(TypeError, lambda: self._factory(object()))
992
993 def test_become_message(self):
994 # Take on the state of another message
995 eMM = email.message_from_string(_sample_message)
996 msg = self._factory()
997 msg._become_message(eMM)
998 self._check_sample(msg)
999
1000 def test_explain_to(self):
1001 # Copy self's format-specific data to other message formats.
1002 # This test is superficial; better ones are in TestMessageConversion.
1003 msg = self._factory()
1004 for class_ in (mailbox.Message, mailbox.MaildirMessage,
1005 mailbox.mboxMessage, mailbox.MHMessage,
1006 mailbox.BabylMessage, mailbox.MMDFMessage):
1007 other_msg = class_()
1008 msg._explain_to(other_msg)
Thomas Woutersb2137042007-02-01 18:02:27 +00001009 other_msg = email.message.Message()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001010 self.assertRaises(TypeError, lambda: msg._explain_to(other_msg))
1011
1012 def _post_initialize_hook(self, msg):
1013 # Overridden by subclasses to check extra things after initialization
1014 pass
1015
1016
1017class TestMaildirMessage(TestMessage):
1018
1019 _factory = mailbox.MaildirMessage
1020
1021 def _post_initialize_hook(self, msg):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001022 self.assertEqual(msg._subdir, 'new')
1023 self.assertEqual(msg._info, '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001024
1025 def test_subdir(self):
1026 # Use get_subdir() and set_subdir()
1027 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001028 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001029 msg.set_subdir('cur')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001030 self.assertEqual(msg.get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001031 msg.set_subdir('new')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001032 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001033 self.assertRaises(ValueError, lambda: msg.set_subdir('tmp'))
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001034 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001035 msg.set_subdir('new')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001036 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001037 self._check_sample(msg)
1038
1039 def test_flags(self):
1040 # Use get_flags(), set_flags(), add_flag(), remove_flag()
1041 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001042 self.assertEqual(msg.get_flags(), '')
1043 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001044 msg.set_flags('F')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001045 self.assertEqual(msg.get_subdir(), 'new')
1046 self.assertEqual(msg.get_flags(), 'F')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001047 msg.set_flags('SDTP')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001048 self.assertEqual(msg.get_flags(), 'DPST')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001049 msg.add_flag('FT')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001050 self.assertEqual(msg.get_flags(), 'DFPST')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001051 msg.remove_flag('TDRP')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001052 self.assertEqual(msg.get_flags(), 'FS')
1053 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001054 self._check_sample(msg)
1055
1056 def test_date(self):
1057 # Use get_date() and set_date()
1058 msg = mailbox.MaildirMessage(_sample_message)
1059 self.assert_(abs(msg.get_date() - time.time()) < 60)
1060 msg.set_date(0.0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001061 self.assertEqual(msg.get_date(), 0.0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001062
1063 def test_info(self):
1064 # Use get_info() and set_info()
1065 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001066 self.assertEqual(msg.get_info(), '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001067 msg.set_info('1,foo=bar')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001068 self.assertEqual(msg.get_info(), '1,foo=bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001069 self.assertRaises(TypeError, lambda: msg.set_info(None))
1070 self._check_sample(msg)
1071
1072 def test_info_and_flags(self):
1073 # Test interaction of info and flag methods
1074 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001075 self.assertEqual(msg.get_info(), '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001076 msg.set_flags('SF')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001077 self.assertEqual(msg.get_flags(), 'FS')
1078 self.assertEqual(msg.get_info(), '2,FS')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079 msg.set_info('1,')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001080 self.assertEqual(msg.get_flags(), '')
1081 self.assertEqual(msg.get_info(), '1,')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001082 msg.remove_flag('RPT')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001083 self.assertEqual(msg.get_flags(), '')
1084 self.assertEqual(msg.get_info(), '1,')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001085 msg.add_flag('D')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001086 self.assertEqual(msg.get_flags(), 'D')
1087 self.assertEqual(msg.get_info(), '2,D')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001088 self._check_sample(msg)
1089
1090
1091class _TestMboxMMDFMessage(TestMessage):
1092
1093 _factory = mailbox._mboxMMDFMessage
1094
1095 def _post_initialize_hook(self, msg):
1096 self._check_from(msg)
1097
1098 def test_initialize_with_unixfrom(self):
1099 # Initialize with a message that already has a _unixfrom attribute
1100 msg = mailbox.Message(_sample_message)
1101 msg.set_unixfrom('From foo@bar blah')
1102 msg = mailbox.mboxMessage(msg)
1103 self.assert_(msg.get_from() == 'foo@bar blah', msg.get_from())
1104
1105 def test_from(self):
1106 # Get and set "From " line
1107 msg = mailbox.mboxMessage(_sample_message)
1108 self._check_from(msg)
1109 msg.set_from('foo bar')
1110 self.assert_(msg.get_from() == 'foo bar')
1111 msg.set_from('foo@bar', True)
1112 self._check_from(msg, 'foo@bar')
1113 msg.set_from('blah@temp', time.localtime())
1114 self._check_from(msg, 'blah@temp')
1115
1116 def test_flags(self):
1117 # Use get_flags(), set_flags(), add_flag(), remove_flag()
1118 msg = mailbox.mboxMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001119 self.assertEqual(msg.get_flags(), '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001120 msg.set_flags('F')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001121 self.assertEqual(msg.get_flags(), 'F')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001122 msg.set_flags('XODR')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001123 self.assertEqual(msg.get_flags(), 'RODX')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001124 msg.add_flag('FA')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001125 self.assertEqual(msg.get_flags(), 'RODFAX')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001126 msg.remove_flag('FDXA')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001127 self.assertEqual(msg.get_flags(), 'RO')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001128 self._check_sample(msg)
1129
1130 def _check_from(self, msg, sender=None):
1131 # Check contents of "From " line
1132 if sender is None:
1133 sender = "MAILER-DAEMON"
1134 self.assert_(re.match(sender + r" \w{3} \w{3} [\d ]\d [\d ]\d:\d{2}:"
1135 r"\d{2} \d{4}", msg.get_from()) is not None)
1136
1137
1138class TestMboxMessage(_TestMboxMMDFMessage):
1139
1140 _factory = mailbox.mboxMessage
1141
1142
1143class TestMHMessage(TestMessage):
1144
1145 _factory = mailbox.MHMessage
1146
1147 def _post_initialize_hook(self, msg):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001148 self.assertEqual(msg._sequences, [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001149
1150 def test_sequences(self):
1151 # Get, set, join, and leave sequences
1152 msg = mailbox.MHMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001153 self.assertEqual(msg.get_sequences(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001154 msg.set_sequences(['foobar'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001155 self.assertEqual(msg.get_sequences(), ['foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001156 msg.set_sequences([])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001157 self.assertEqual(msg.get_sequences(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001158 msg.add_sequence('unseen')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001159 self.assertEqual(msg.get_sequences(), ['unseen'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001160 msg.add_sequence('flagged')
1161 self.assert_(msg.get_sequences() == ['unseen', 'flagged'])
1162 msg.add_sequence('flagged')
1163 self.assert_(msg.get_sequences() == ['unseen', 'flagged'])
1164 msg.remove_sequence('unseen')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001165 self.assertEqual(msg.get_sequences(), ['flagged'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001166 msg.add_sequence('foobar')
1167 self.assert_(msg.get_sequences() == ['flagged', 'foobar'])
1168 msg.remove_sequence('replied')
1169 self.assert_(msg.get_sequences() == ['flagged', 'foobar'])
1170 msg.set_sequences(['foobar', 'replied'])
1171 self.assert_(msg.get_sequences() == ['foobar', 'replied'])
1172
1173
1174class TestBabylMessage(TestMessage):
1175
1176 _factory = mailbox.BabylMessage
1177
1178 def _post_initialize_hook(self, msg):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001179 self.assertEqual(msg._labels, [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001180
1181 def test_labels(self):
1182 # Get, set, join, and leave labels
1183 msg = mailbox.BabylMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001184 self.assertEqual(msg.get_labels(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001185 msg.set_labels(['foobar'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001186 self.assertEqual(msg.get_labels(), ['foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001187 msg.set_labels([])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001188 self.assertEqual(msg.get_labels(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001189 msg.add_label('filed')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001190 self.assertEqual(msg.get_labels(), ['filed'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001191 msg.add_label('resent')
1192 self.assert_(msg.get_labels() == ['filed', 'resent'])
1193 msg.add_label('resent')
1194 self.assert_(msg.get_labels() == ['filed', 'resent'])
1195 msg.remove_label('filed')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001196 self.assertEqual(msg.get_labels(), ['resent'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001197 msg.add_label('foobar')
1198 self.assert_(msg.get_labels() == ['resent', 'foobar'])
1199 msg.remove_label('unseen')
1200 self.assert_(msg.get_labels() == ['resent', 'foobar'])
1201 msg.set_labels(['foobar', 'answered'])
1202 self.assert_(msg.get_labels() == ['foobar', 'answered'])
1203
1204 def test_visible(self):
1205 # Get, set, and update visible headers
1206 msg = mailbox.BabylMessage(_sample_message)
1207 visible = msg.get_visible()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001208 self.assertEqual(visible.keys(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001209 self.assert_(visible.get_payload() is None)
1210 visible['User-Agent'] = 'FooBar 1.0'
1211 visible['X-Whatever'] = 'Blah'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001212 self.assertEqual(msg.get_visible().keys(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001213 msg.set_visible(visible)
1214 visible = msg.get_visible()
1215 self.assert_(visible.keys() == ['User-Agent', 'X-Whatever'])
1216 self.assert_(visible['User-Agent'] == 'FooBar 1.0')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001217 self.assertEqual(visible['X-Whatever'], 'Blah')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001218 self.assert_(visible.get_payload() is None)
1219 msg.update_visible()
1220 self.assert_(visible.keys() == ['User-Agent', 'X-Whatever'])
1221 self.assert_(visible.get_payload() is None)
1222 visible = msg.get_visible()
1223 self.assert_(visible.keys() == ['User-Agent', 'Date', 'From', 'To',
1224 'Subject'])
1225 for header in ('User-Agent', 'Date', 'From', 'To', 'Subject'):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001226 self.assertEqual(visible[header], msg[header])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001227
1228
1229class TestMMDFMessage(_TestMboxMMDFMessage):
1230
1231 _factory = mailbox.MMDFMessage
1232
1233
1234class TestMessageConversion(TestBase):
1235
1236 def test_plain_to_x(self):
1237 # Convert Message to all formats
1238 for class_ in (mailbox.Message, mailbox.MaildirMessage,
1239 mailbox.mboxMessage, mailbox.MHMessage,
1240 mailbox.BabylMessage, mailbox.MMDFMessage):
1241 msg_plain = mailbox.Message(_sample_message)
1242 msg = class_(msg_plain)
1243 self._check_sample(msg)
1244
1245 def test_x_to_plain(self):
1246 # Convert all formats to Message
1247 for class_ in (mailbox.Message, mailbox.MaildirMessage,
1248 mailbox.mboxMessage, mailbox.MHMessage,
1249 mailbox.BabylMessage, mailbox.MMDFMessage):
1250 msg = class_(_sample_message)
1251 msg_plain = mailbox.Message(msg)
1252 self._check_sample(msg_plain)
1253
1254 def test_x_to_invalid(self):
1255 # Convert all formats to an invalid format
1256 for class_ in (mailbox.Message, mailbox.MaildirMessage,
1257 mailbox.mboxMessage, mailbox.MHMessage,
1258 mailbox.BabylMessage, mailbox.MMDFMessage):
1259 self.assertRaises(TypeError, lambda: class_(False))
1260
1261 def test_maildir_to_maildir(self):
1262 # Convert MaildirMessage to MaildirMessage
1263 msg_maildir = mailbox.MaildirMessage(_sample_message)
1264 msg_maildir.set_flags('DFPRST')
1265 msg_maildir.set_subdir('cur')
1266 date = msg_maildir.get_date()
1267 msg = mailbox.MaildirMessage(msg_maildir)
1268 self._check_sample(msg)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001269 self.assertEqual(msg.get_flags(), 'DFPRST')
1270 self.assertEqual(msg.get_subdir(), 'cur')
1271 self.assertEqual(msg.get_date(), date)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001272
1273 def test_maildir_to_mboxmmdf(self):
1274 # Convert MaildirMessage to mboxmessage and MMDFMessage
1275 pairs = (('D', ''), ('F', 'F'), ('P', ''), ('R', 'A'), ('S', 'R'),
1276 ('T', 'D'), ('DFPRST', 'RDFA'))
1277 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1278 msg_maildir = mailbox.MaildirMessage(_sample_message)
1279 msg_maildir.set_date(0.0)
1280 for setting, result in pairs:
1281 msg_maildir.set_flags(setting)
1282 msg = class_(msg_maildir)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001283 self.assertEqual(msg.get_flags(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001284 self.assert_(msg.get_from() == 'MAILER-DAEMON %s' %
1285 time.asctime(time.gmtime(0.0)))
1286 msg_maildir.set_subdir('cur')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001287 self.assertEqual(class_(msg_maildir).get_flags(), 'RODFA')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001288
1289 def test_maildir_to_mh(self):
1290 # Convert MaildirMessage to MHMessage
1291 msg_maildir = mailbox.MaildirMessage(_sample_message)
1292 pairs = (('D', ['unseen']), ('F', ['unseen', 'flagged']),
1293 ('P', ['unseen']), ('R', ['unseen', 'replied']), ('S', []),
1294 ('T', ['unseen']), ('DFPRST', ['replied', 'flagged']))
1295 for setting, result in pairs:
1296 msg_maildir.set_flags(setting)
1297 self.assert_(mailbox.MHMessage(msg_maildir).get_sequences() == \
1298 result)
1299
1300 def test_maildir_to_babyl(self):
1301 # Convert MaildirMessage to Babyl
1302 msg_maildir = mailbox.MaildirMessage(_sample_message)
1303 pairs = (('D', ['unseen']), ('F', ['unseen']),
1304 ('P', ['unseen', 'forwarded']), ('R', ['unseen', 'answered']),
1305 ('S', []), ('T', ['unseen', 'deleted']),
1306 ('DFPRST', ['deleted', 'answered', 'forwarded']))
1307 for setting, result in pairs:
1308 msg_maildir.set_flags(setting)
1309 self.assert_(mailbox.BabylMessage(msg_maildir).get_labels() == \
1310 result)
1311
1312 def test_mboxmmdf_to_maildir(self):
1313 # Convert mboxMessage and MMDFMessage to MaildirMessage
1314 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1315 msg_mboxMMDF = class_(_sample_message)
1316 msg_mboxMMDF.set_from('foo@bar', time.gmtime(0.0))
1317 pairs = (('R', 'S'), ('O', ''), ('D', 'T'), ('F', 'F'), ('A', 'R'),
1318 ('RODFA', 'FRST'))
1319 for setting, result in pairs:
1320 msg_mboxMMDF.set_flags(setting)
1321 msg = mailbox.MaildirMessage(msg_mboxMMDF)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001322 self.assertEqual(msg.get_flags(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001323 self.assert_(msg.get_date() == 0.0, msg.get_date())
1324 msg_mboxMMDF.set_flags('O')
1325 self.assert_(mailbox.MaildirMessage(msg_mboxMMDF).get_subdir() == \
1326 'cur')
1327
1328 def test_mboxmmdf_to_mboxmmdf(self):
1329 # Convert mboxMessage and MMDFMessage to mboxMessage and MMDFMessage
1330 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1331 msg_mboxMMDF = class_(_sample_message)
1332 msg_mboxMMDF.set_flags('RODFA')
1333 msg_mboxMMDF.set_from('foo@bar')
1334 for class2_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1335 msg2 = class2_(msg_mboxMMDF)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001336 self.assertEqual(msg2.get_flags(), 'RODFA')
1337 self.assertEqual(msg2.get_from(), 'foo@bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001338
1339 def test_mboxmmdf_to_mh(self):
1340 # Convert mboxMessage and MMDFMessage to MHMessage
1341 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1342 msg_mboxMMDF = class_(_sample_message)
1343 pairs = (('R', []), ('O', ['unseen']), ('D', ['unseen']),
1344 ('F', ['unseen', 'flagged']),
1345 ('A', ['unseen', 'replied']),
1346 ('RODFA', ['replied', 'flagged']))
1347 for setting, result in pairs:
1348 msg_mboxMMDF.set_flags(setting)
1349 self.assert_(mailbox.MHMessage(msg_mboxMMDF).get_sequences() \
1350 == result)
1351
1352 def test_mboxmmdf_to_babyl(self):
1353 # Convert mboxMessage and MMDFMessage to BabylMessage
1354 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1355 msg = class_(_sample_message)
1356 pairs = (('R', []), ('O', ['unseen']),
1357 ('D', ['unseen', 'deleted']), ('F', ['unseen']),
1358 ('A', ['unseen', 'answered']),
1359 ('RODFA', ['deleted', 'answered']))
1360 for setting, result in pairs:
1361 msg.set_flags(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001362 self.assertEqual(mailbox.BabylMessage(msg).get_labels(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363
1364 def test_mh_to_maildir(self):
1365 # Convert MHMessage to MaildirMessage
1366 pairs = (('unseen', ''), ('replied', 'RS'), ('flagged', 'FS'))
1367 for setting, result in pairs:
1368 msg = mailbox.MHMessage(_sample_message)
1369 msg.add_sequence(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001370 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), result)
1371 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001372 msg = mailbox.MHMessage(_sample_message)
1373 msg.add_sequence('unseen')
1374 msg.add_sequence('replied')
1375 msg.add_sequence('flagged')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001376 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), 'FR')
1377 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001378
1379 def test_mh_to_mboxmmdf(self):
1380 # Convert MHMessage to mboxMessage and MMDFMessage
1381 pairs = (('unseen', 'O'), ('replied', 'ROA'), ('flagged', 'ROF'))
1382 for setting, result in pairs:
1383 msg = mailbox.MHMessage(_sample_message)
1384 msg.add_sequence(setting)
1385 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001386 self.assertEqual(class_(msg).get_flags(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001387 msg = mailbox.MHMessage(_sample_message)
1388 msg.add_sequence('unseen')
1389 msg.add_sequence('replied')
1390 msg.add_sequence('flagged')
1391 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001392 self.assertEqual(class_(msg).get_flags(), 'OFA')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001393
1394 def test_mh_to_mh(self):
1395 # Convert MHMessage to MHMessage
1396 msg = mailbox.MHMessage(_sample_message)
1397 msg.add_sequence('unseen')
1398 msg.add_sequence('replied')
1399 msg.add_sequence('flagged')
1400 self.assert_(mailbox.MHMessage(msg).get_sequences() == \
1401 ['unseen', 'replied', 'flagged'])
1402
1403 def test_mh_to_babyl(self):
1404 # Convert MHMessage to BabylMessage
1405 pairs = (('unseen', ['unseen']), ('replied', ['answered']),
1406 ('flagged', []))
1407 for setting, result in pairs:
1408 msg = mailbox.MHMessage(_sample_message)
1409 msg.add_sequence(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001410 self.assertEqual(mailbox.BabylMessage(msg).get_labels(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001411 msg = mailbox.MHMessage(_sample_message)
1412 msg.add_sequence('unseen')
1413 msg.add_sequence('replied')
1414 msg.add_sequence('flagged')
1415 self.assert_(mailbox.BabylMessage(msg).get_labels() == \
1416 ['unseen', 'answered'])
1417
1418 def test_babyl_to_maildir(self):
1419 # Convert BabylMessage to MaildirMessage
1420 pairs = (('unseen', ''), ('deleted', 'ST'), ('filed', 'S'),
1421 ('answered', 'RS'), ('forwarded', 'PS'), ('edited', 'S'),
1422 ('resent', 'PS'))
1423 for setting, result in pairs:
1424 msg = mailbox.BabylMessage(_sample_message)
1425 msg.add_label(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001426 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), result)
1427 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001428 msg = mailbox.BabylMessage(_sample_message)
1429 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1430 'edited', 'resent'):
1431 msg.add_label(label)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001432 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), 'PRT')
1433 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001434
1435 def test_babyl_to_mboxmmdf(self):
1436 # Convert BabylMessage to mboxMessage and MMDFMessage
1437 pairs = (('unseen', 'O'), ('deleted', 'ROD'), ('filed', 'RO'),
1438 ('answered', 'ROA'), ('forwarded', 'RO'), ('edited', 'RO'),
1439 ('resent', 'RO'))
1440 for setting, result in pairs:
1441 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1442 msg = mailbox.BabylMessage(_sample_message)
1443 msg.add_label(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001444 self.assertEqual(class_(msg).get_flags(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001445 msg = mailbox.BabylMessage(_sample_message)
1446 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1447 'edited', 'resent'):
1448 msg.add_label(label)
1449 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001450 self.assertEqual(class_(msg).get_flags(), 'ODA')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001451
1452 def test_babyl_to_mh(self):
1453 # Convert BabylMessage to MHMessage
1454 pairs = (('unseen', ['unseen']), ('deleted', []), ('filed', []),
1455 ('answered', ['replied']), ('forwarded', []), ('edited', []),
1456 ('resent', []))
1457 for setting, result in pairs:
1458 msg = mailbox.BabylMessage(_sample_message)
1459 msg.add_label(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001460 self.assertEqual(mailbox.MHMessage(msg).get_sequences(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001461 msg = mailbox.BabylMessage(_sample_message)
1462 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1463 'edited', 'resent'):
1464 msg.add_label(label)
1465 self.assert_(mailbox.MHMessage(msg).get_sequences() == \
1466 ['unseen', 'replied'])
1467
1468 def test_babyl_to_babyl(self):
1469 # Convert BabylMessage to BabylMessage
1470 msg = mailbox.BabylMessage(_sample_message)
1471 msg.update_visible()
1472 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1473 'edited', 'resent'):
1474 msg.add_label(label)
1475 msg2 = mailbox.BabylMessage(msg)
1476 self.assert_(msg2.get_labels() == ['unseen', 'deleted', 'filed',
1477 'answered', 'forwarded', 'edited',
1478 'resent'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001479 self.assertEqual(msg.get_visible().keys(), msg2.get_visible().keys())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001480 for key in msg.get_visible().keys():
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001481 self.assertEqual(msg.get_visible()[key], msg2.get_visible()[key])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001482
1483
1484class TestProxyFileBase(TestBase):
1485
1486 def _test_read(self, proxy):
1487 # Read by byte
1488 proxy.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001489 self.assertEqual(proxy.read(), 'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001490 proxy.seek(1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001491 self.assertEqual(proxy.read(), 'ar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001492 proxy.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001493 self.assertEqual(proxy.read(2), 'ba')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001494 proxy.seek(1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001495 self.assertEqual(proxy.read(-1), 'ar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001496 proxy.seek(2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001497 self.assertEqual(proxy.read(1000), 'r')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001498
1499 def _test_readline(self, proxy):
1500 # Read by line
1501 proxy.seek(0)
1502 self.assert_(proxy.readline() == 'foo' + os.linesep)
1503 self.assert_(proxy.readline() == 'bar' + os.linesep)
1504 self.assert_(proxy.readline() == 'fred' + os.linesep)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001505 self.assertEqual(proxy.readline(), 'bob')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001506 proxy.seek(2)
1507 self.assert_(proxy.readline() == 'o' + os.linesep)
1508 proxy.seek(6 + 2 * len(os.linesep))
1509 self.assert_(proxy.readline() == 'fred' + os.linesep)
1510 proxy.seek(6 + 2 * len(os.linesep))
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001511 self.assertEqual(proxy.readline(2), 'fr')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001512 self.assert_(proxy.readline(-10) == 'ed' + os.linesep)
1513
1514 def _test_readlines(self, proxy):
1515 # Read multiple lines
1516 proxy.seek(0)
1517 self.assert_(proxy.readlines() == ['foo' + os.linesep,
1518 'bar' + os.linesep,
1519 'fred' + os.linesep, 'bob'])
1520 proxy.seek(0)
1521 self.assert_(proxy.readlines(2) == ['foo' + os.linesep])
1522 proxy.seek(3 + len(os.linesep))
1523 self.assert_(proxy.readlines(4 + len(os.linesep)) ==
1524 ['bar' + os.linesep, 'fred' + os.linesep])
1525 proxy.seek(3)
1526 self.assert_(proxy.readlines(1000) == [os.linesep, 'bar' + os.linesep,
1527 'fred' + os.linesep, 'bob'])
1528
1529 def _test_iteration(self, proxy):
1530 # Iterate by line
1531 proxy.seek(0)
1532 iterator = iter(proxy)
Georg Brandla18af4e2007-04-21 15:47:16 +00001533 self.assert_(next(iterator) == 'foo' + os.linesep)
1534 self.assert_(next(iterator) == 'bar' + os.linesep)
1535 self.assert_(next(iterator) == 'fred' + os.linesep)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001536 self.assertEqual(next(iterator), 'bob')
Georg Brandla18af4e2007-04-21 15:47:16 +00001537 self.assertRaises(StopIteration, next, iterator)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001538
1539 def _test_seek_and_tell(self, proxy):
1540 # Seek and use tell to check position
1541 proxy.seek(3)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001542 self.assertEqual(proxy.tell(), 3)
1543 self.assertEqual(proxy.read(len(os.linesep)), os.linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001544 proxy.seek(2, 1)
1545 self.assert_(proxy.read(1 + len(os.linesep)) == 'r' + os.linesep)
1546 proxy.seek(-3 - len(os.linesep), 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001547 self.assertEqual(proxy.read(3), 'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001548 proxy.seek(2, 0)
1549 self.assert_(proxy.read() == 'o' + os.linesep + 'bar' + os.linesep)
1550 proxy.seek(100)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001551 self.assertEqual(proxy.read(), '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001552
1553 def _test_close(self, proxy):
1554 # Close a file
1555 proxy.close()
1556 self.assertRaises(AttributeError, lambda: proxy.close())
1557
1558
1559class TestProxyFile(TestProxyFileBase):
1560
1561 def setUp(self):
1562 self._path = test_support.TESTFN
1563 self._file = open(self._path, 'wb+')
1564
1565 def tearDown(self):
1566 self._file.close()
1567 self._delete_recursively(self._path)
1568
1569 def test_initialize(self):
1570 # Initialize and check position
1571 self._file.write('foo')
1572 pos = self._file.tell()
1573 proxy0 = mailbox._ProxyFile(self._file)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001574 self.assertEqual(proxy0.tell(), pos)
1575 self.assertEqual(self._file.tell(), pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001576 proxy1 = mailbox._ProxyFile(self._file, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001577 self.assertEqual(proxy1.tell(), 0)
1578 self.assertEqual(self._file.tell(), pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001579
1580 def test_read(self):
1581 self._file.write('bar')
1582 self._test_read(mailbox._ProxyFile(self._file))
1583
1584 def test_readline(self):
1585 self._file.write('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
1586 os.linesep))
1587 self._test_readline(mailbox._ProxyFile(self._file))
1588
1589 def test_readlines(self):
1590 self._file.write('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
1591 os.linesep))
1592 self._test_readlines(mailbox._ProxyFile(self._file))
1593
1594 def test_iteration(self):
1595 self._file.write('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
1596 os.linesep))
1597 self._test_iteration(mailbox._ProxyFile(self._file))
1598
1599 def test_seek_and_tell(self):
1600 self._file.write('foo%sbar%s' % (os.linesep, os.linesep))
1601 self._test_seek_and_tell(mailbox._ProxyFile(self._file))
1602
1603 def test_close(self):
1604 self._file.write('foo%sbar%s' % (os.linesep, os.linesep))
1605 self._test_close(mailbox._ProxyFile(self._file))
1606
1607
1608class TestPartialFile(TestProxyFileBase):
1609
1610 def setUp(self):
1611 self._path = test_support.TESTFN
1612 self._file = open(self._path, 'wb+')
1613
1614 def tearDown(self):
1615 self._file.close()
1616 self._delete_recursively(self._path)
1617
1618 def test_initialize(self):
1619 # Initialize and check position
1620 self._file.write('foo' + os.linesep + 'bar')
1621 pos = self._file.tell()
1622 proxy = mailbox._PartialFile(self._file, 2, 5)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001623 self.assertEqual(proxy.tell(), 0)
1624 self.assertEqual(self._file.tell(), pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001625
1626 def test_read(self):
1627 self._file.write('***bar***')
1628 self._test_read(mailbox._PartialFile(self._file, 3, 6))
1629
1630 def test_readline(self):
1631 self._file.write('!!!!!foo%sbar%sfred%sbob!!!!!' %
1632 (os.linesep, os.linesep, os.linesep))
1633 self._test_readline(mailbox._PartialFile(self._file, 5,
1634 18 + 3 * len(os.linesep)))
1635
1636 def test_readlines(self):
1637 self._file.write('foo%sbar%sfred%sbob?????' %
1638 (os.linesep, os.linesep, os.linesep))
1639 self._test_readlines(mailbox._PartialFile(self._file, 0,
1640 13 + 3 * len(os.linesep)))
1641
1642 def test_iteration(self):
1643 self._file.write('____foo%sbar%sfred%sbob####' %
1644 (os.linesep, os.linesep, os.linesep))
1645 self._test_iteration(mailbox._PartialFile(self._file, 4,
1646 17 + 3 * len(os.linesep)))
1647
1648 def test_seek_and_tell(self):
1649 self._file.write('(((foo%sbar%s$$$' % (os.linesep, os.linesep))
1650 self._test_seek_and_tell(mailbox._PartialFile(self._file, 3,
1651 9 + 2 * len(os.linesep)))
1652
1653 def test_close(self):
1654 self._file.write('&foo%sbar%s^' % (os.linesep, os.linesep))
1655 self._test_close(mailbox._PartialFile(self._file, 1,
1656 6 + 3 * len(os.linesep)))
1657
1658
1659## Start: tests from the original module (for backward compatibility).
1660
Skip Montanaro5253da12004-07-24 19:56:03 +00001661FROM_ = "From some.body@dummy.domain Sat Jul 24 13:43:35 2004\n"
Fred Drakec02bc3e2001-05-21 20:23:21 +00001662DUMMY_MESSAGE = """\
1663From: some.body@dummy.domain
1664To: me@my.domain
Skip Montanaro5253da12004-07-24 19:56:03 +00001665Subject: Simple Test
Fred Drakec02bc3e2001-05-21 20:23:21 +00001666
1667This is a dummy message.
1668"""
1669
Fred Drakec02bc3e2001-05-21 20:23:21 +00001670class MaildirTestCase(unittest.TestCase):
1671
1672 def setUp(self):
1673 # create a new maildir mailbox to work with:
1674 self._dir = test_support.TESTFN
1675 os.mkdir(self._dir)
1676 os.mkdir(os.path.join(self._dir, "cur"))
1677 os.mkdir(os.path.join(self._dir, "tmp"))
1678 os.mkdir(os.path.join(self._dir, "new"))
1679 self._counter = 1
1680 self._msgfiles = []
1681
1682 def tearDown(self):
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001683 list(map(os.unlink, self._msgfiles))
Fred Drakec02bc3e2001-05-21 20:23:21 +00001684 os.rmdir(os.path.join(self._dir, "cur"))
1685 os.rmdir(os.path.join(self._dir, "tmp"))
1686 os.rmdir(os.path.join(self._dir, "new"))
1687 os.rmdir(self._dir)
1688
Skip Montanaro5253da12004-07-24 19:56:03 +00001689 def createMessage(self, dir, mbox=False):
Jack Jansen97df7b62001-06-19 20:20:05 +00001690 t = int(time.time() % 1000000)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001691 pid = self._counter
1692 self._counter += 1
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001693 filename = os.extsep.join((str(t), str(pid), "myhostname", "mydomain"))
Fred Drakec02bc3e2001-05-21 20:23:21 +00001694 tmpname = os.path.join(self._dir, "tmp", filename)
1695 newname = os.path.join(self._dir, dir, filename)
1696 fp = open(tmpname, "w")
1697 self._msgfiles.append(tmpname)
Skip Montanaro5253da12004-07-24 19:56:03 +00001698 if mbox:
1699 fp.write(FROM_)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001700 fp.write(DUMMY_MESSAGE)
1701 fp.close()
Tim Peters6626c1f2001-05-22 16:29:01 +00001702 if hasattr(os, "link"):
1703 os.link(tmpname, newname)
1704 else:
1705 fp = open(newname, "w")
1706 fp.write(DUMMY_MESSAGE)
1707 fp.close()
Fred Drakec02bc3e2001-05-21 20:23:21 +00001708 self._msgfiles.append(newname)
Skip Montanaro5253da12004-07-24 19:56:03 +00001709 return tmpname
Fred Drakec02bc3e2001-05-21 20:23:21 +00001710
1711 def test_empty_maildir(self):
1712 """Test an empty maildir mailbox"""
1713 # Test for regression on bug #117490:
1714 # Make sure the boxes attribute actually gets set.
1715 self.mbox = mailbox.Maildir(test_support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001716 #self.assert_(hasattr(self.mbox, "boxes"))
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001717 #self.assertEqual(len(self.mbox.boxes), 0)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001718 self.assert_(self.mbox.next() is None)
1719 self.assert_(self.mbox.next() is None)
1720
1721 def test_nonempty_maildir_cur(self):
1722 self.createMessage("cur")
1723 self.mbox = mailbox.Maildir(test_support.TESTFN)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001724 #self.assertEqual(len(self.mbox.boxes), 1)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001725 self.assert_(self.mbox.next() is not None)
1726 self.assert_(self.mbox.next() is None)
1727 self.assert_(self.mbox.next() is None)
1728
1729 def test_nonempty_maildir_new(self):
1730 self.createMessage("new")
1731 self.mbox = mailbox.Maildir(test_support.TESTFN)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001732 #self.assertEqual(len(self.mbox.boxes), 1)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001733 self.assert_(self.mbox.next() is not None)
1734 self.assert_(self.mbox.next() is None)
1735 self.assert_(self.mbox.next() is None)
1736
1737 def test_nonempty_maildir_both(self):
1738 self.createMessage("cur")
1739 self.createMessage("new")
1740 self.mbox = mailbox.Maildir(test_support.TESTFN)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001741 #self.assertEqual(len(self.mbox.boxes), 2)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001742 self.assert_(self.mbox.next() is not None)
1743 self.assert_(self.mbox.next() is not None)
1744 self.assert_(self.mbox.next() is None)
1745 self.assert_(self.mbox.next() is None)
Fred Drake0aaed272000-10-23 13:39:15 +00001746
Skip Montanaro5253da12004-07-24 19:56:03 +00001747 def test_unix_mbox(self):
1748 ### should be better!
Thomas Woutersb2137042007-02-01 18:02:27 +00001749 import email.parser
Skip Montanaro5253da12004-07-24 19:56:03 +00001750 fname = self.createMessage("cur", True)
1751 n = 0
1752 for msg in mailbox.PortableUnixMailbox(open(fname),
Thomas Woutersb2137042007-02-01 18:02:27 +00001753 email.parser.Parser().parse):
Skip Montanaro5253da12004-07-24 19:56:03 +00001754 n += 1
1755 self.assertEqual(msg["subject"], "Simple Test")
1756 self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE))
1757 self.assertEqual(n, 1)
1758
Thomas Wouters477c8d52006-05-27 19:21:47 +00001759## End: classes from the original module (for backward compatibility).
1760
1761
1762_sample_message = """\
1763Return-Path: <gkj@gregorykjohnson.com>
1764X-Original-To: gkj+person@localhost
1765Delivered-To: gkj+person@localhost
1766Received: from localhost (localhost [127.0.0.1])
1767 by andy.gregorykjohnson.com (Postfix) with ESMTP id 356ED9DD17
1768 for <gkj+person@localhost>; Wed, 13 Jul 2005 17:23:16 -0400 (EDT)
1769Delivered-To: gkj@sundance.gregorykjohnson.com
1770Received: from localhost [127.0.0.1]
1771 by localhost with POP3 (fetchmail-6.2.5)
1772 for gkj+person@localhost (single-drop); Wed, 13 Jul 2005 17:23:16 -0400 (EDT)
1773Received: from andy.gregorykjohnson.com (andy.gregorykjohnson.com [64.32.235.228])
1774 by sundance.gregorykjohnson.com (Postfix) with ESMTP id 5B056316746
1775 for <gkj@gregorykjohnson.com>; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)
1776Received: by andy.gregorykjohnson.com (Postfix, from userid 1000)
1777 id 490CD9DD17; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)
1778Date: Wed, 13 Jul 2005 17:23:11 -0400
1779From: "Gregory K. Johnson" <gkj@gregorykjohnson.com>
1780To: gkj@gregorykjohnson.com
1781Subject: Sample message
1782Message-ID: <20050713212311.GC4701@andy.gregorykjohnson.com>
1783Mime-Version: 1.0
1784Content-Type: multipart/mixed; boundary="NMuMz9nt05w80d4+"
1785Content-Disposition: inline
1786User-Agent: Mutt/1.5.9i
1787
1788
1789--NMuMz9nt05w80d4+
1790Content-Type: text/plain; charset=us-ascii
1791Content-Disposition: inline
1792
1793This is a sample message.
1794
1795--
1796Gregory K. Johnson
1797
1798--NMuMz9nt05w80d4+
1799Content-Type: application/octet-stream
1800Content-Disposition: attachment; filename="text.gz"
1801Content-Transfer-Encoding: base64
1802
1803H4sICM2D1UIAA3RleHQAC8nILFYAokSFktSKEoW0zJxUPa7wzJIMhZLyfIWczLzUYj0uAHTs
18043FYlAAAA
1805
1806--NMuMz9nt05w80d4+--
1807"""
1808
1809_sample_headers = {
1810 "Return-Path":"<gkj@gregorykjohnson.com>",
1811 "X-Original-To":"gkj+person@localhost",
1812 "Delivered-To":"gkj+person@localhost",
1813 "Received":"""from localhost (localhost [127.0.0.1])
1814 by andy.gregorykjohnson.com (Postfix) with ESMTP id 356ED9DD17
1815 for <gkj+person@localhost>; Wed, 13 Jul 2005 17:23:16 -0400 (EDT)""",
1816 "Delivered-To":"gkj@sundance.gregorykjohnson.com",
1817 "Received":"""from localhost [127.0.0.1]
1818 by localhost with POP3 (fetchmail-6.2.5)
1819 for gkj+person@localhost (single-drop); Wed, 13 Jul 2005 17:23:16 -0400 (EDT)""",
1820 "Received":"""from andy.gregorykjohnson.com (andy.gregorykjohnson.com [64.32.235.228])
1821 by sundance.gregorykjohnson.com (Postfix) with ESMTP id 5B056316746
1822 for <gkj@gregorykjohnson.com>; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)""",
1823 "Received":"""by andy.gregorykjohnson.com (Postfix, from userid 1000)
1824 id 490CD9DD17; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)""",
1825 "Date":"Wed, 13 Jul 2005 17:23:11 -0400",
1826 "From":""""Gregory K. Johnson" <gkj@gregorykjohnson.com>""",
1827 "To":"gkj@gregorykjohnson.com",
1828 "Subject":"Sample message",
1829 "Mime-Version":"1.0",
1830 "Content-Type":"""multipart/mixed; boundary="NMuMz9nt05w80d4+\"""",
1831 "Content-Disposition":"inline",
1832 "User-Agent": "Mutt/1.5.9i" }
1833
1834_sample_payloads = ("""This is a sample message.
1835
1836--
1837Gregory K. Johnson
1838""",
1839"""H4sICM2D1UIAA3RleHQAC8nILFYAokSFktSKEoW0zJxUPa7wzJIMhZLyfIWczLzUYj0uAHTs
18403FYlAAAA
1841""")
Fred Drake0aaed272000-10-23 13:39:15 +00001842
Fred Drakec02bc3e2001-05-21 20:23:21 +00001843
Fred Drake2e2be372001-09-20 21:33:42 +00001844def test_main():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001845 tests = (TestMailboxSuperclass, TestMaildir, TestMbox, TestMMDF, TestMH,
1846 TestBabyl, TestMessage, TestMaildirMessage, TestMboxMessage,
1847 TestMHMessage, TestBabylMessage, TestMMDFMessage,
1848 TestMessageConversion, TestProxyFile, TestPartialFile,
1849 MaildirTestCase)
1850 test_support.run_unittest(*tests)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001851 test_support.reap_children()
Fred Drake2e2be372001-09-20 21:33:42 +00001852
1853
Thomas Wouters477c8d52006-05-27 19:21:47 +00001854if __name__ == '__main__':
Fred Drake2e2be372001-09-20 21:33:42 +00001855 test_main()