blob: 472dfe728c5a1dc8fc85a337b9d01bedb30f88cc [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
Guido van Rossum34d19282007-08-09 01:03:29 +000010import io
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):
Thomas Wouters477c8d52006-05-27 19:21:47 +000061 self._delete_recursively(self._path)
62
63 def test_add(self):
64 # Add copies of a sample message
65 keys = []
66 keys.append(self._box.add(self._template % 0))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000067 self.assertEqual(len(self._box), 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000068 keys.append(self._box.add(mailbox.Message(_sample_message)))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000069 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +000070 keys.append(self._box.add(email.message_from_string(_sample_message)))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000071 self.assertEqual(len(self._box), 3)
Guido van Rossum34d19282007-08-09 01:03:29 +000072 keys.append(self._box.add(io.StringIO(_sample_message)))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000073 self.assertEqual(len(self._box), 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +000074 keys.append(self._box.add(_sample_message))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000075 self.assertEqual(len(self._box), 5)
Guido van Rossumea834472007-07-27 05:17:50 +000076 self.assertEqual(self._box.get_string(keys[0]), self._template % 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000077 for i in (1, 2, 3, 4):
78 self._check_sample(self._box[keys[i]])
79
80 def test_remove(self):
81 # Remove messages using remove()
82 self._test_remove_or_delitem(self._box.remove)
83
84 def test_delitem(self):
85 # Remove messages using __delitem__()
86 self._test_remove_or_delitem(self._box.__delitem__)
87
88 def _test_remove_or_delitem(self, method):
89 # (Used by test_remove() and test_delitem().)
90 key0 = self._box.add(self._template % 0)
91 key1 = self._box.add(self._template % 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +000092 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +000093 method(key0)
94 l = len(self._box)
95 self.assert_(l == 1, "actual l: %s" % l)
96 self.assertRaises(KeyError, lambda: self._box[key0])
97 self.assertRaises(KeyError, lambda: method(key0))
Guido van Rossumea834472007-07-27 05:17:50 +000098 self.assertEqual(self._box.get_string(key1), self._template % 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000099 key2 = self._box.add(self._template % 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000100 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000101 method(key2)
102 l = len(self._box)
103 self.assert_(l == 1, "actual l: %s" % l)
104 self.assertRaises(KeyError, lambda: self._box[key2])
105 self.assertRaises(KeyError, lambda: method(key2))
Guido van Rossumea834472007-07-27 05:17:50 +0000106 self.assertEqual(self._box.get_string(key1), self._template % 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000107 method(key1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000108 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109 self.assertRaises(KeyError, lambda: self._box[key1])
110 self.assertRaises(KeyError, lambda: method(key1))
111
112 def test_discard(self, repetitions=10):
113 # Discard messages
114 key0 = self._box.add(self._template % 0)
115 key1 = self._box.add(self._template % 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000116 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000117 self._box.discard(key0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000118 self.assertEqual(len(self._box), 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000119 self.assertRaises(KeyError, lambda: self._box[key0])
120 self._box.discard(key0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000121 self.assertEqual(len(self._box), 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000122 self.assertRaises(KeyError, lambda: self._box[key0])
123
124 def test_get(self):
125 # Retrieve messages using get()
126 key0 = self._box.add(self._template % 0)
127 msg = self._box.get(key0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000128 self.assertEqual(msg['from'], 'foo')
129 self.assertEqual(msg.get_payload(), '0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000130 self.assert_(self._box.get('foo') is None)
131 self.assert_(self._box.get('foo', False) is False)
132 self._box.close()
133 self._box = self._factory(self._path, factory=rfc822.Message)
134 key1 = self._box.add(self._template % 1)
135 msg = self._box.get(key1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000136 self.assertEqual(msg['from'], 'foo')
137 self.assertEqual(msg.fp.read(), '1')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000138
139 def test_getitem(self):
140 # Retrieve message using __getitem__()
141 key0 = self._box.add(self._template % 0)
142 msg = self._box[key0]
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000143 self.assertEqual(msg['from'], 'foo')
144 self.assertEqual(msg.get_payload(), '0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000145 self.assertRaises(KeyError, lambda: self._box['foo'])
146 self._box.discard(key0)
147 self.assertRaises(KeyError, lambda: self._box[key0])
148
149 def test_get_message(self):
150 # Get Message representations of messages
151 key0 = self._box.add(self._template % 0)
152 key1 = self._box.add(_sample_message)
153 msg0 = self._box.get_message(key0)
154 self.assert_(isinstance(msg0, mailbox.Message))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000155 self.assertEqual(msg0['from'], 'foo')
156 self.assertEqual(msg0.get_payload(), '0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000157 self._check_sample(self._box.get_message(key1))
158
159 def test_get_string(self):
160 # Get string representations of messages
161 key0 = self._box.add(self._template % 0)
162 key1 = self._box.add(_sample_message)
Guido van Rossumea834472007-07-27 05:17:50 +0000163 self.assertEqual(self._box.get_string(key0), self._template % 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000164 self.assertEqual(self._box.get_string(key1), _sample_message)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000165
166 def test_get_file(self):
167 # Get file representations of messages
168 key0 = self._box.add(self._template % 0)
169 key1 = self._box.add(_sample_message)
Guido van Rossumea834472007-07-27 05:17:50 +0000170 self.assertEqual(self._box.get_file(key0).read().replace(os.linesep, '\n'),
171 self._template % 0)
172 self.assertEqual(self._box.get_file(key1).read().replace(os.linesep, '\n'),
173 _sample_message)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000174
175 def test_iterkeys(self):
176 # Get keys using iterkeys()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000177 self._check_iteration(self._box.keys, do_keys=True, do_values=False)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000178
179 def test_keys(self):
180 # Get keys using keys()
181 self._check_iteration(self._box.keys, do_keys=True, do_values=False)
182
183 def test_itervalues(self):
184 # Get values using itervalues()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000185 self._check_iteration(self._box.values, do_keys=False,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000186 do_values=True)
187
188 def test_iter(self):
189 # Get values using __iter__()
190 self._check_iteration(self._box.__iter__, do_keys=False,
191 do_values=True)
192
193 def test_values(self):
194 # Get values using values()
195 self._check_iteration(self._box.values, do_keys=False, do_values=True)
196
197 def test_iteritems(self):
198 # Get keys and values using iteritems()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000199 self._check_iteration(self._box.items, do_keys=True,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000200 do_values=True)
201
202 def test_items(self):
203 # Get keys and values using items()
204 self._check_iteration(self._box.items, do_keys=True, do_values=True)
205
206 def _check_iteration(self, method, do_keys, do_values, repetitions=10):
207 for value in method():
208 self.fail("Not empty")
209 keys, values = [], []
Guido van Rossum805365e2007-05-07 22:24:25 +0000210 for i in range(repetitions):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000211 keys.append(self._box.add(self._template % i))
212 values.append(self._template % i)
213 if do_keys and not do_values:
214 returned_keys = list(method())
215 elif do_values and not do_keys:
216 returned_values = list(method())
217 else:
218 returned_keys, returned_values = [], []
219 for key, value in method():
220 returned_keys.append(key)
221 returned_values.append(value)
222 if do_keys:
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000223 self.assertEqual(len(keys), len(returned_keys))
224 self.assertEqual(set(keys), set(returned_keys))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000225 if do_values:
226 count = 0
227 for value in returned_values:
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000228 self.assertEqual(value['from'], 'foo')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000229 self.assert_(int(value.get_payload()) < repetitions)
230 count += 1
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000231 self.assertEqual(len(values), count)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000232
Thomas Wouters477c8d52006-05-27 19:21:47 +0000233 def test_contains(self):
234 # Check existence of keys using __contains__()
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000235 method = self._box.__contains__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000236 self.assert_(not method('foo'))
237 key0 = self._box.add(self._template % 0)
238 self.assert_(method(key0))
239 self.assert_(not method('foo'))
240 key1 = self._box.add(self._template % 1)
241 self.assert_(method(key1))
242 self.assert_(method(key0))
243 self.assert_(not method('foo'))
244 self._box.remove(key0)
245 self.assert_(not method(key0))
246 self.assert_(method(key1))
247 self.assert_(not method('foo'))
248 self._box.remove(key1)
249 self.assert_(not method(key1))
250 self.assert_(not method(key0))
251 self.assert_(not method('foo'))
252
253 def test_len(self, repetitions=10):
254 # Get message count
255 keys = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000256 for i in range(repetitions):
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000257 self.assertEqual(len(self._box), i)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000258 keys.append(self._box.add(self._template % i))
Guido van Rossumea834472007-07-27 05:17:50 +0000259 self.assertEqual(len(self._box), i + 1)
Guido van Rossum805365e2007-05-07 22:24:25 +0000260 for i in range(repetitions):
Guido van Rossumea834472007-07-27 05:17:50 +0000261 self.assertEqual(len(self._box), repetitions - i)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000262 self._box.remove(keys[i])
Guido van Rossumea834472007-07-27 05:17:50 +0000263 self.assertEqual(len(self._box), repetitions - i - 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000264
265 def test_set_item(self):
266 # Modify messages using __setitem__()
267 key0 = self._box.add(self._template % 'original 0')
Guido van Rossumea834472007-07-27 05:17:50 +0000268 self.assertEqual(self._box.get_string(key0),
269 self._template % 'original 0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000270 key1 = self._box.add(self._template % 'original 1')
Guido van Rossumea834472007-07-27 05:17:50 +0000271 self.assertEqual(self._box.get_string(key1),
272 self._template % 'original 1')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273 self._box[key0] = self._template % 'changed 0'
Guido van Rossumea834472007-07-27 05:17:50 +0000274 self.assertEqual(self._box.get_string(key0),
275 self._template % 'changed 0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000276 self._box[key1] = self._template % 'changed 1'
Guido van Rossumea834472007-07-27 05:17:50 +0000277 self.assertEqual(self._box.get_string(key1),
278 self._template % 'changed 1')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000279 self._box[key0] = _sample_message
280 self._check_sample(self._box[key0])
281 self._box[key1] = self._box[key0]
282 self._check_sample(self._box[key1])
283 self._box[key0] = self._template % 'original 0'
Guido van Rossumea834472007-07-27 05:17:50 +0000284 self.assertEqual(self._box.get_string(key0),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000285 self._template % 'original 0')
286 self._check_sample(self._box[key1])
287 self.assertRaises(KeyError,
288 lambda: self._box.__setitem__('foo', 'bar'))
289 self.assertRaises(KeyError, lambda: self._box['foo'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000290 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000291
292 def test_clear(self, iterations=10):
293 # Remove all messages using clear()
294 keys = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000295 for i in range(iterations):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000296 self._box.add(self._template % i)
297 for i, key in enumerate(keys):
298 self.assert_(self._box.get_string(key) == self._template % i)
299 self._box.clear()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000300 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000301 for i, key in enumerate(keys):
302 self.assertRaises(KeyError, lambda: self._box.get_string(key))
303
304 def test_pop(self):
305 # Get and remove a message using pop()
306 key0 = self._box.add(self._template % 0)
307 self.assert_(key0 in self._box)
308 key1 = self._box.add(self._template % 1)
309 self.assert_(key1 in self._box)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000310 self.assertEqual(self._box.pop(key0).get_payload(), '0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000311 self.assert_(key0 not in self._box)
312 self.assert_(key1 in self._box)
313 key2 = self._box.add(self._template % 2)
314 self.assert_(key2 in self._box)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000315 self.assertEqual(self._box.pop(key2).get_payload(), '2')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000316 self.assert_(key2 not in self._box)
317 self.assert_(key1 in self._box)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000318 self.assertEqual(self._box.pop(key1).get_payload(), '1')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000319 self.assert_(key1 not in self._box)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000320 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000321
322 def test_popitem(self, iterations=10):
323 # Get and remove an arbitrary (key, message) using popitem()
324 keys = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000325 for i in range(10):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000326 keys.append(self._box.add(self._template % i))
327 seen = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000328 for i in range(10):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000329 key, msg = self._box.popitem()
330 self.assert_(key in keys)
331 self.assert_(key not in seen)
332 seen.append(key)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000333 self.assertEqual(int(msg.get_payload()), keys.index(key))
334 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000335 for key in keys:
336 self.assertRaises(KeyError, lambda: self._box[key])
337
338 def test_update(self):
339 # Modify multiple messages using update()
340 key0 = self._box.add(self._template % 'original 0')
341 key1 = self._box.add(self._template % 'original 1')
342 key2 = self._box.add(self._template % 'original 2')
343 self._box.update({key0: self._template % 'changed 0',
344 key2: _sample_message})
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000345 self.assertEqual(len(self._box), 3)
Guido van Rossumea834472007-07-27 05:17:50 +0000346 self.assertEqual(self._box.get_string(key0),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000347 self._template % 'changed 0')
Guido van Rossumea834472007-07-27 05:17:50 +0000348 self.assertEqual(self._box.get_string(key1),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000349 self._template % 'original 1')
350 self._check_sample(self._box[key2])
351 self._box.update([(key2, self._template % 'changed 2'),
352 (key1, self._template % 'changed 1'),
353 (key0, self._template % 'original 0')])
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000354 self.assertEqual(len(self._box), 3)
Guido van Rossumea834472007-07-27 05:17:50 +0000355 self.assertEqual(self._box.get_string(key0),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000356 self._template % 'original 0')
Guido van Rossumea834472007-07-27 05:17:50 +0000357 self.assertEqual(self._box.get_string(key1),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000358 self._template % 'changed 1')
Guido van Rossumea834472007-07-27 05:17:50 +0000359 self.assertEqual(self._box.get_string(key2),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000360 self._template % 'changed 2')
361 self.assertRaises(KeyError,
362 lambda: self._box.update({'foo': 'bar',
363 key0: self._template % "changed 0"}))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000364 self.assertEqual(len(self._box), 3)
Guido van Rossumea834472007-07-27 05:17:50 +0000365 self.assertEqual(self._box.get_string(key0),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000366 self._template % "changed 0")
Guido van Rossumea834472007-07-27 05:17:50 +0000367 self.assertEqual(self._box.get_string(key1),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000368 self._template % "changed 1")
Guido van Rossumea834472007-07-27 05:17:50 +0000369 self.assertEqual(self._box.get_string(key2),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000370 self._template % "changed 2")
371
372 def test_flush(self):
373 # Write changes to disk
374 self._test_flush_or_close(self._box.flush)
375
376 def test_lock_unlock(self):
377 # Lock and unlock the mailbox
378 self.assert_(not os.path.exists(self._get_lock_path()))
379 self._box.lock()
380 self.assert_(os.path.exists(self._get_lock_path()))
381 self._box.unlock()
382 self.assert_(not os.path.exists(self._get_lock_path()))
383
384 def test_close(self):
385 # Close mailbox and flush changes to disk
386 self._test_flush_or_close(self._box.close)
387
388 def _test_flush_or_close(self, method):
Guido van Rossum805365e2007-05-07 22:24:25 +0000389 contents = [self._template % i for i in range(3)]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000390 self._box.add(contents[0])
391 self._box.add(contents[1])
392 self._box.add(contents[2])
393 method()
394 self._box = self._factory(self._path)
395 keys = self._box.keys()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000396 self.assertEqual(len(keys), 3)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000397 for key in keys:
398 self.assert_(self._box.get_string(key) in contents)
399
400 def test_dump_message(self):
401 # Write message representations to disk
402 for input in (email.message_from_string(_sample_message),
Guido van Rossum34d19282007-08-09 01:03:29 +0000403 _sample_message, io.StringIO(_sample_message)):
404 output = io.StringIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000405 self._box._dump_message(input, output)
406 self.assert_(output.getvalue() ==
407 _sample_message.replace('\n', os.linesep))
Guido van Rossum34d19282007-08-09 01:03:29 +0000408 output = io.StringIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000409 self.assertRaises(TypeError,
410 lambda: self._box._dump_message(None, output))
411
412 def _get_lock_path(self):
413 # Return the path of the dot lock file. May be overridden.
414 return self._path + '.lock'
415
416
417class TestMailboxSuperclass(TestBase):
418
419 def test_notimplemented(self):
420 # Test that all Mailbox methods raise NotImplementedException.
421 box = mailbox.Mailbox('path')
422 self.assertRaises(NotImplementedError, lambda: box.add(''))
423 self.assertRaises(NotImplementedError, lambda: box.remove(''))
424 self.assertRaises(NotImplementedError, lambda: box.__delitem__(''))
425 self.assertRaises(NotImplementedError, lambda: box.discard(''))
426 self.assertRaises(NotImplementedError, lambda: box.__setitem__('', ''))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000427 self.assertRaises(NotImplementedError, lambda: box.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000428 self.assertRaises(NotImplementedError, lambda: box.keys())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000429 self.assertRaises(NotImplementedError, lambda: box.values().__next__())
430 self.assertRaises(NotImplementedError, lambda: box.__iter__().__next__())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431 self.assertRaises(NotImplementedError, lambda: box.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000432 self.assertRaises(NotImplementedError, lambda: box.items().next())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433 self.assertRaises(NotImplementedError, lambda: box.items())
434 self.assertRaises(NotImplementedError, lambda: box.get(''))
435 self.assertRaises(NotImplementedError, lambda: box.__getitem__(''))
436 self.assertRaises(NotImplementedError, lambda: box.get_message(''))
437 self.assertRaises(NotImplementedError, lambda: box.get_string(''))
438 self.assertRaises(NotImplementedError, lambda: box.get_file(''))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000439 self.assertRaises(NotImplementedError, lambda: '' in box)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000440 self.assertRaises(NotImplementedError, lambda: box.__contains__(''))
441 self.assertRaises(NotImplementedError, lambda: box.__len__())
442 self.assertRaises(NotImplementedError, lambda: box.clear())
443 self.assertRaises(NotImplementedError, lambda: box.pop(''))
444 self.assertRaises(NotImplementedError, lambda: box.popitem())
445 self.assertRaises(NotImplementedError, lambda: box.update((('', ''),)))
446 self.assertRaises(NotImplementedError, lambda: box.flush())
447 self.assertRaises(NotImplementedError, lambda: box.lock())
448 self.assertRaises(NotImplementedError, lambda: box.unlock())
449 self.assertRaises(NotImplementedError, lambda: box.close())
450
451
452class TestMaildir(TestMailbox):
453
454 _factory = lambda self, path, factory=None: mailbox.Maildir(path, factory)
455
456 def setUp(self):
457 TestMailbox.setUp(self)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000458 if os.name in ('nt', 'os2') or sys.platform == 'cygwin':
Thomas Wouters477c8d52006-05-27 19:21:47 +0000459 self._box.colon = '!'
460
461 def test_add_MM(self):
462 # Add a MaildirMessage instance
463 msg = mailbox.MaildirMessage(self._template % 0)
464 msg.set_subdir('cur')
465 msg.set_info('foo')
466 key = self._box.add(msg)
467 self.assert_(os.path.exists(os.path.join(self._path, 'cur', '%s%sfoo' %
468 (key, self._box.colon))))
469
470 def test_get_MM(self):
471 # Get a MaildirMessage instance
472 msg = mailbox.MaildirMessage(self._template % 0)
473 msg.set_subdir('cur')
474 msg.set_flags('RF')
475 key = self._box.add(msg)
476 msg_returned = self._box.get_message(key)
477 self.assert_(isinstance(msg_returned, mailbox.MaildirMessage))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000478 self.assertEqual(msg_returned.get_subdir(), 'cur')
479 self.assertEqual(msg_returned.get_flags(), 'FR')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000480
481 def test_set_MM(self):
482 # Set with a MaildirMessage instance
483 msg0 = mailbox.MaildirMessage(self._template % 0)
484 msg0.set_flags('TP')
485 key = self._box.add(msg0)
486 msg_returned = self._box.get_message(key)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000487 self.assertEqual(msg_returned.get_subdir(), 'new')
488 self.assertEqual(msg_returned.get_flags(), 'PT')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000489 msg1 = mailbox.MaildirMessage(self._template % 1)
490 self._box[key] = msg1
491 msg_returned = self._box.get_message(key)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000492 self.assertEqual(msg_returned.get_subdir(), 'new')
493 self.assertEqual(msg_returned.get_flags(), '')
494 self.assertEqual(msg_returned.get_payload(), '1')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000495 msg2 = mailbox.MaildirMessage(self._template % 2)
496 msg2.set_info('2,S')
497 self._box[key] = msg2
498 self._box[key] = self._template % 3
499 msg_returned = self._box.get_message(key)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000500 self.assertEqual(msg_returned.get_subdir(), 'new')
501 self.assertEqual(msg_returned.get_flags(), 'S')
502 self.assertEqual(msg_returned.get_payload(), '3')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000503
504 def test_initialize_new(self):
505 # Initialize a non-existent mailbox
506 self.tearDown()
507 self._box = mailbox.Maildir(self._path)
508 self._check_basics(factory=rfc822.Message)
509 self._delete_recursively(self._path)
510 self._box = self._factory(self._path, factory=None)
511 self._check_basics()
512
513 def test_initialize_existing(self):
514 # Initialize an existing mailbox
515 self.tearDown()
516 for subdir in '', 'tmp', 'new', 'cur':
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000517 os.mkdir(os.path.normpath(os.path.join(self._path, subdir)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000518 self._box = mailbox.Maildir(self._path)
519 self._check_basics(factory=rfc822.Message)
520 self._box = mailbox.Maildir(self._path, factory=None)
521 self._check_basics()
522
523 def _check_basics(self, factory=None):
524 # (Used by test_open_new() and test_open_existing().)
525 self.assertEqual(self._box._path, os.path.abspath(self._path))
526 self.assertEqual(self._box._factory, factory)
527 for subdir in '', 'tmp', 'new', 'cur':
528 path = os.path.join(self._path, subdir)
529 mode = os.stat(path)[stat.ST_MODE]
530 self.assert_(stat.S_ISDIR(mode), "Not a directory: '%s'" % path)
531
532 def test_list_folders(self):
533 # List folders
534 self._box.add_folder('one')
535 self._box.add_folder('two')
536 self._box.add_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000537 self.assertEqual(len(self._box.list_folders()), 3)
Guido van Rossumea834472007-07-27 05:17:50 +0000538 self.assertEqual(set(self._box.list_folders()),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539 set(('one', 'two', 'three')))
540
541 def test_get_folder(self):
542 # Open folders
543 self._box.add_folder('foo.bar')
544 folder0 = self._box.get_folder('foo.bar')
545 folder0.add(self._template % 'bar')
546 self.assert_(os.path.isdir(os.path.join(self._path, '.foo.bar')))
547 folder1 = self._box.get_folder('foo.bar')
Guido van Rossumea834472007-07-27 05:17:50 +0000548 self.assertEqual(folder1.get_string(folder1.keys()[0]),
549 self._template % 'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000550
551 def test_add_and_remove_folders(self):
552 # Delete folders
553 self._box.add_folder('one')
554 self._box.add_folder('two')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000555 self.assertEqual(len(self._box.list_folders()), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556 self.assert_(set(self._box.list_folders()) == set(('one', 'two')))
557 self._box.remove_folder('one')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000558 self.assertEqual(len(self._box.list_folders()), 1)
559 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000560 self._box.add_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000561 self.assertEqual(len(self._box.list_folders()), 2)
Guido van Rossumea834472007-07-27 05:17:50 +0000562 self.assertEqual(set(self._box.list_folders()), set(('two', 'three')))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000563 self._box.remove_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000564 self.assertEqual(len(self._box.list_folders()), 1)
565 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000566 self._box.remove_folder('two')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000567 self.assertEqual(len(self._box.list_folders()), 0)
568 self.assertEqual(self._box.list_folders(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569
570 def test_clean(self):
571 # Remove old files from 'tmp'
572 foo_path = os.path.join(self._path, 'tmp', 'foo')
573 bar_path = os.path.join(self._path, 'tmp', 'bar')
574 f = open(foo_path, 'w')
575 f.write("@")
576 f.close()
577 f = open(bar_path, 'w')
578 f.write("@")
579 f.close()
580 self._box.clean()
581 self.assert_(os.path.exists(foo_path))
582 self.assert_(os.path.exists(bar_path))
583 foo_stat = os.stat(foo_path)
584 os.utime(foo_path, (time.time() - 129600 - 2,
585 foo_stat.st_mtime))
586 self._box.clean()
587 self.assert_(not os.path.exists(foo_path))
588 self.assert_(os.path.exists(bar_path))
589
590 def test_create_tmp(self, repetitions=10):
591 # Create files in tmp directory
592 hostname = socket.gethostname()
593 if '/' in hostname:
594 hostname = hostname.replace('/', r'\057')
595 if ':' in hostname:
596 hostname = hostname.replace(':', r'\072')
597 pid = os.getpid()
598 pattern = re.compile(r"(?P<time>\d+)\.M(?P<M>\d{1,6})P(?P<P>\d+)"
599 r"Q(?P<Q>\d+)\.(?P<host>[^:/]+)")
600 previous_groups = None
Guido van Rossum805365e2007-05-07 22:24:25 +0000601 for x in range(repetitions):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000602 tmp_file = self._box._create_tmp()
603 head, tail = os.path.split(tmp_file.name)
604 self.assertEqual(head, os.path.abspath(os.path.join(self._path,
605 "tmp")),
606 "File in wrong location: '%s'" % head)
607 match = pattern.match(tail)
608 self.assert_(match != None, "Invalid file name: '%s'" % tail)
609 groups = match.groups()
610 if previous_groups != None:
611 self.assert_(int(groups[0] >= previous_groups[0]),
612 "Non-monotonic seconds: '%s' before '%s'" %
613 (previous_groups[0], groups[0]))
614 self.assert_(int(groups[1] >= previous_groups[1]) or
615 groups[0] != groups[1],
616 "Non-monotonic milliseconds: '%s' before '%s'" %
617 (previous_groups[1], groups[1]))
Guido van Rossumea834472007-07-27 05:17:50 +0000618 self.assertEqual(int(groups[2]), pid,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000619 "Process ID mismatch: '%s' should be '%s'" %
620 (groups[2], pid))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000621 self.assertEqual(int(groups[3]), int(previous_groups[3]) + 1,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000622 "Non-sequential counter: '%s' before '%s'" %
623 (previous_groups[3], groups[3]))
Guido van Rossumea834472007-07-27 05:17:50 +0000624 self.assertEqual(groups[4], hostname,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000625 "Host name mismatch: '%s' should be '%s'" %
626 (groups[4], hostname))
627 previous_groups = groups
628 tmp_file.write(_sample_message)
629 tmp_file.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000630 self.assertEqual(tmp_file.read(), _sample_message)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000631 tmp_file.close()
632 file_count = len(os.listdir(os.path.join(self._path, "tmp")))
Guido van Rossumea834472007-07-27 05:17:50 +0000633 self.assertEqual(file_count, repetitions,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000634 "Wrong file count: '%s' should be '%s'" %
635 (file_count, repetitions))
636
637 def test_refresh(self):
638 # Update the table of contents
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000639 self.assertEqual(self._box._toc, {})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000640 key0 = self._box.add(self._template % 0)
641 key1 = self._box.add(self._template % 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000642 self.assertEqual(self._box._toc, {})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000643 self._box._refresh()
Guido van Rossumea834472007-07-27 05:17:50 +0000644 self.assertEqual(self._box._toc, {key0: os.path.join('new', key0),
645 key1: os.path.join('new', key1)})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000646 key2 = self._box.add(self._template % 2)
Guido van Rossumea834472007-07-27 05:17:50 +0000647 self.assertEqual(self._box._toc, {key0: os.path.join('new', key0),
648 key1: os.path.join('new', key1)})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000649 self._box._refresh()
Guido van Rossumea834472007-07-27 05:17:50 +0000650 self.assertEqual(self._box._toc, {key0: os.path.join('new', key0),
651 key1: os.path.join('new', key1),
652 key2: os.path.join('new', key2)})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000653
654 def test_lookup(self):
655 # Look up message subpaths in the TOC
656 self.assertRaises(KeyError, lambda: self._box._lookup('foo'))
657 key0 = self._box.add(self._template % 0)
Guido van Rossumea834472007-07-27 05:17:50 +0000658 self.assertEqual(self._box._lookup(key0), os.path.join('new', key0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000659 os.remove(os.path.join(self._path, 'new', key0))
Guido van Rossumea834472007-07-27 05:17:50 +0000660 self.assertEqual(self._box._toc, {key0: os.path.join('new', key0)})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000661 self.assertRaises(KeyError, lambda: self._box._lookup(key0))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000662 self.assertEqual(self._box._toc, {})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000663
664 def test_lock_unlock(self):
665 # Lock and unlock the mailbox. For Maildir, this does nothing.
666 self._box.lock()
667 self._box.unlock()
668
Thomas Wouters89f507f2006-12-13 04:49:30 +0000669 def test_folder (self):
670 # Test for bug #1569790: verify that folders returned by .get_folder()
671 # use the same factory function.
672 def dummy_factory (s):
673 return None
674 box = self._factory(self._path, factory=dummy_factory)
675 folder = box.add_folder('folder1')
676 self.assert_(folder._factory is dummy_factory)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000677
Thomas Wouters89f507f2006-12-13 04:49:30 +0000678 folder1_alias = box.get_folder('folder1')
679 self.assert_(folder1_alias._factory is dummy_factory)
680
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000681 def test_directory_in_folder (self):
682 # Test that mailboxes still work if there's a stray extra directory
683 # in a folder.
684 for i in range(10):
685 self._box.add(mailbox.Message(_sample_message))
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000686
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000687 # Create a stray directory
688 os.mkdir(os.path.join(self._path, 'cur', 'stray-dir'))
689
690 # Check that looping still works with the directory present.
691 for msg in self._box:
692 pass
Thomas Wouters477c8d52006-05-27 19:21:47 +0000693
694class _TestMboxMMDF(TestMailbox):
695
696 def tearDown(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000697 self._delete_recursively(self._path)
698 for lock_remnant in glob.glob(self._path + '.*'):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000699 test_support.unlink(lock_remnant)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000700
701 def test_add_from_string(self):
702 # Add a string starting with 'From ' to the mailbox
703 key = self._box.add('From foo@bar blah\nFrom: foo\n\n0')
Guido van Rossumea834472007-07-27 05:17:50 +0000704 self.assertEqual(self._box[key].get_from(), 'foo@bar blah')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000705 self.assertEqual(self._box[key].get_payload(), '0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000706
707 def test_add_mbox_or_mmdf_message(self):
708 # Add an mboxMessage or MMDFMessage
709 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
710 msg = class_('From foo@bar blah\nFrom: foo\n\n0')
711 key = self._box.add(msg)
712
713 def test_open_close_open(self):
714 # Open and inspect previously-created mailbox
Guido van Rossum805365e2007-05-07 22:24:25 +0000715 values = [self._template % i for i in range(3)]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716 for value in values:
717 self._box.add(value)
718 self._box.close()
719 mtime = os.path.getmtime(self._path)
720 self._box = self._factory(self._path)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000721 self.assertEqual(len(self._box), 3)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000722 for key in self._box.keys():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000723 self.assert_(self._box.get_string(key) in values)
724 self._box.close()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000725 self.assertEqual(mtime, os.path.getmtime(self._path))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000726
727 def test_add_and_close(self):
728 # Verifying that closing a mailbox doesn't change added items
729 self._box.add(_sample_message)
Guido van Rossum805365e2007-05-07 22:24:25 +0000730 for i in range(3):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000731 self._box.add(self._template % i)
732 self._box.add(_sample_message)
733 self._box._file.flush()
734 self._box._file.seek(0)
735 contents = self._box._file.read()
736 self._box.close()
Guido van Rossumea834472007-07-27 05:17:50 +0000737 self.assertEqual(contents, open(self._path, 'r').read())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000738 self._box = self._factory(self._path)
739
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000740 def test_lock_conflict(self):
741 # Fork off a subprocess that will lock the file for 2 seconds,
742 # unlock it, and then exit.
743 if not hasattr(os, 'fork'):
744 return
745 pid = os.fork()
746 if pid == 0:
747 # In the child, lock the mailbox.
Guido van Rossum62cbc8a2007-04-09 00:41:25 +0000748 try:
749 self._box.lock()
750 time.sleep(2)
751 self._box.unlock()
752 finally:
753 os._exit(0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000754
755 # In the parent, sleep a bit to give the child time to acquire
756 # the lock.
757 time.sleep(0.5)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000758 try:
759 self.assertRaises(mailbox.ExternalClashError,
760 self._box.lock)
761 finally:
762 # Wait for child to exit. Locking should now succeed.
763 exited_pid, status = os.waitpid(pid, 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000764
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000765 self._box.lock()
766 self._box.unlock()
767
Thomas Wouters89f507f2006-12-13 04:49:30 +0000768 def test_relock(self):
769 # Test case for bug #1575506: the mailbox class was locking the
770 # wrong file object in its flush() method.
771 msg = "Subject: sub\n\nbody\n"
772 key1 = self._box.add(msg)
773 self._box.flush()
774 self._box.close()
775
776 self._box = self._factory(self._path)
777 self._box.lock()
778 key2 = self._box.add(msg)
779 self._box.flush()
780 self.assert_(self._box._locked)
781 self._box.close()
782
783
Thomas Wouters477c8d52006-05-27 19:21:47 +0000784
785class TestMbox(_TestMboxMMDF):
786
787 _factory = lambda self, path, factory=None: mailbox.mbox(path, factory)
788
789
790class TestMMDF(_TestMboxMMDF):
791
792 _factory = lambda self, path, factory=None: mailbox.MMDF(path, factory)
793
794
795class TestMH(TestMailbox):
796
797 _factory = lambda self, path, factory=None: mailbox.MH(path, factory)
798
799 def test_list_folders(self):
800 # List folders
801 self._box.add_folder('one')
802 self._box.add_folder('two')
803 self._box.add_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000804 self.assertEqual(len(self._box.list_folders()), 3)
Guido van Rossumea834472007-07-27 05:17:50 +0000805 self.assertEqual(set(self._box.list_folders()),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000806 set(('one', 'two', 'three')))
807
808 def test_get_folder(self):
809 # Open folders
Thomas Wouters89f507f2006-12-13 04:49:30 +0000810 def dummy_factory (s):
811 return None
812 self._box = self._factory(self._path, dummy_factory)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000813
Thomas Wouters89f507f2006-12-13 04:49:30 +0000814 new_folder = self._box.add_folder('foo.bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000815 folder0 = self._box.get_folder('foo.bar')
816 folder0.add(self._template % 'bar')
817 self.assert_(os.path.isdir(os.path.join(self._path, 'foo.bar')))
818 folder1 = self._box.get_folder('foo.bar')
Guido van Rossumea834472007-07-27 05:17:50 +0000819 self.assertEqual(folder1.get_string(folder1.keys()[0]),
820 self._template % 'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000821
Thomas Wouters89f507f2006-12-13 04:49:30 +0000822 # Test for bug #1569790: verify that folders returned by .get_folder()
823 # use the same factory function.
824 self.assert_(new_folder._factory is self._box._factory)
825 self.assert_(folder0._factory is self._box._factory)
826
Thomas Wouters477c8d52006-05-27 19:21:47 +0000827 def test_add_and_remove_folders(self):
828 # Delete folders
829 self._box.add_folder('one')
830 self._box.add_folder('two')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000831 self.assertEqual(len(self._box.list_folders()), 2)
Guido van Rossumea834472007-07-27 05:17:50 +0000832 self.assertEqual(set(self._box.list_folders()), set(('one', 'two')))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000833 self._box.remove_folder('one')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000834 self.assertEqual(len(self._box.list_folders()), 1)
835 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000836 self._box.add_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000837 self.assertEqual(len(self._box.list_folders()), 2)
Guido van Rossumea834472007-07-27 05:17:50 +0000838 self.assertEqual(set(self._box.list_folders()), set(('two', 'three')))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000839 self._box.remove_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000840 self.assertEqual(len(self._box.list_folders()), 1)
841 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000842 self._box.remove_folder('two')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000843 self.assertEqual(len(self._box.list_folders()), 0)
844 self.assertEqual(self._box.list_folders(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +0000845
846 def test_sequences(self):
847 # Get and set sequences
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000848 self.assertEqual(self._box.get_sequences(), {})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000849 msg0 = mailbox.MHMessage(self._template % 0)
850 msg0.add_sequence('foo')
851 key0 = self._box.add(msg0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000852 self.assertEqual(self._box.get_sequences(), {'foo':[key0]})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000853 msg1 = mailbox.MHMessage(self._template % 1)
854 msg1.set_sequences(['bar', 'replied', 'foo'])
855 key1 = self._box.add(msg1)
Guido van Rossumea834472007-07-27 05:17:50 +0000856 self.assertEqual(self._box.get_sequences(),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000857 {'foo':[key0, key1], 'bar':[key1], 'replied':[key1]})
858 msg0.set_sequences(['flagged'])
859 self._box[key0] = msg0
Guido van Rossumea834472007-07-27 05:17:50 +0000860 self.assertEqual(self._box.get_sequences(),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000861 {'foo':[key1], 'bar':[key1], 'replied':[key1],
862 'flagged':[key0]})
863 self._box.remove(key1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000864 self.assertEqual(self._box.get_sequences(), {'flagged':[key0]})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000865
866 def test_pack(self):
867 # Pack the contents of the mailbox
868 msg0 = mailbox.MHMessage(self._template % 0)
869 msg1 = mailbox.MHMessage(self._template % 1)
870 msg2 = mailbox.MHMessage(self._template % 2)
871 msg3 = mailbox.MHMessage(self._template % 3)
872 msg0.set_sequences(['foo', 'unseen'])
873 msg1.set_sequences(['foo'])
874 msg2.set_sequences(['foo', 'flagged'])
875 msg3.set_sequences(['foo', 'bar', 'replied'])
876 key0 = self._box.add(msg0)
877 key1 = self._box.add(msg1)
878 key2 = self._box.add(msg2)
879 key3 = self._box.add(msg3)
Guido van Rossumea834472007-07-27 05:17:50 +0000880 self.assertEqual(self._box.get_sequences(),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000881 {'foo':[key0,key1,key2,key3], 'unseen':[key0],
882 'flagged':[key2], 'bar':[key3], 'replied':[key3]})
883 self._box.remove(key2)
Guido van Rossumea834472007-07-27 05:17:50 +0000884 self.assertEqual(self._box.get_sequences(),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000885 {'foo':[key0,key1,key3], 'unseen':[key0], 'bar':[key3],
886 'replied':[key3]})
887 self._box.pack()
888 self.assert_(self._box.keys() == [1, 2, 3])
889 key0 = key0
890 key1 = key0 + 1
891 key2 = key1 + 1
Guido van Rossumea834472007-07-27 05:17:50 +0000892 self.assertEqual(self._box.get_sequences(),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000893 {'foo':[1, 2, 3], 'unseen':[1], 'bar':[3], 'replied':[3]})
894
Thomas Wouters89f507f2006-12-13 04:49:30 +0000895 # Test case for packing while holding the mailbox locked.
896 key0 = self._box.add(msg1)
897 key1 = self._box.add(msg1)
898 key2 = self._box.add(msg1)
899 key3 = self._box.add(msg1)
900
901 self._box.remove(key0)
902 self._box.remove(key2)
903 self._box.lock()
904 self._box.pack()
905 self._box.unlock()
Guido van Rossumea834472007-07-27 05:17:50 +0000906 self.assertEqual(self._box.get_sequences(),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000907 {'foo':[1, 2, 3, 4, 5],
908 'unseen':[1], 'bar':[3], 'replied':[3]})
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000909
Thomas Wouters477c8d52006-05-27 19:21:47 +0000910 def _get_lock_path(self):
911 return os.path.join(self._path, '.mh_sequences.lock')
912
913
914class TestBabyl(TestMailbox):
915
916 _factory = lambda self, path, factory=None: mailbox.Babyl(path, factory)
917
918 def tearDown(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000919 self._delete_recursively(self._path)
920 for lock_remnant in glob.glob(self._path + '.*'):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000921 test_support.unlink(lock_remnant)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000922
923 def test_labels(self):
924 # Get labels from the mailbox
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000925 self.assertEqual(self._box.get_labels(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +0000926 msg0 = mailbox.BabylMessage(self._template % 0)
927 msg0.add_label('foo')
928 key0 = self._box.add(msg0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000929 self.assertEqual(self._box.get_labels(), ['foo'])
Thomas Wouters477c8d52006-05-27 19:21:47 +0000930 msg1 = mailbox.BabylMessage(self._template % 1)
931 msg1.set_labels(['bar', 'answered', 'foo'])
932 key1 = self._box.add(msg1)
Guido van Rossumea834472007-07-27 05:17:50 +0000933 self.assertEqual(set(self._box.get_labels()), set(['foo', 'bar']))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000934 msg0.set_labels(['blah', 'filed'])
935 self._box[key0] = msg0
Guido van Rossumea834472007-07-27 05:17:50 +0000936 self.assertEqual(set(self._box.get_labels()),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000937 set(['foo', 'bar', 'blah']))
938 self._box.remove(key1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000939 self.assertEqual(set(self._box.get_labels()), set(['blah']))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000940
941
942class TestMessage(TestBase):
943
944 _factory = mailbox.Message # Overridden by subclasses to reuse tests
945
946 def setUp(self):
947 self._path = test_support.TESTFN
948
949 def tearDown(self):
950 self._delete_recursively(self._path)
951
952 def test_initialize_with_eMM(self):
Thomas Woutersb2137042007-02-01 18:02:27 +0000953 # Initialize based on email.message.Message instance
Thomas Wouters477c8d52006-05-27 19:21:47 +0000954 eMM = email.message_from_string(_sample_message)
955 msg = self._factory(eMM)
956 self._post_initialize_hook(msg)
957 self._check_sample(msg)
958
959 def test_initialize_with_string(self):
960 # Initialize based on string
961 msg = self._factory(_sample_message)
962 self._post_initialize_hook(msg)
963 self._check_sample(msg)
964
965 def test_initialize_with_file(self):
966 # Initialize based on contents of file
967 f = open(self._path, 'w+')
968 f.write(_sample_message)
969 f.seek(0)
970 msg = self._factory(f)
971 self._post_initialize_hook(msg)
972 self._check_sample(msg)
973 f.close()
974
975 def test_initialize_with_nothing(self):
976 # Initialize without arguments
977 msg = self._factory()
978 self._post_initialize_hook(msg)
Thomas Woutersb2137042007-02-01 18:02:27 +0000979 self.assert_(isinstance(msg, email.message.Message))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000980 self.assert_(isinstance(msg, mailbox.Message))
981 self.assert_(isinstance(msg, self._factory))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000982 self.assertEqual(msg.keys(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +0000983 self.assert_(not msg.is_multipart())
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000984 self.assertEqual(msg.get_payload(), None)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000985
986 def test_initialize_incorrectly(self):
987 # Initialize with invalid argument
988 self.assertRaises(TypeError, lambda: self._factory(object()))
989
990 def test_become_message(self):
991 # Take on the state of another message
992 eMM = email.message_from_string(_sample_message)
993 msg = self._factory()
994 msg._become_message(eMM)
995 self._check_sample(msg)
996
997 def test_explain_to(self):
998 # Copy self's format-specific data to other message formats.
999 # This test is superficial; better ones are in TestMessageConversion.
1000 msg = self._factory()
1001 for class_ in (mailbox.Message, mailbox.MaildirMessage,
1002 mailbox.mboxMessage, mailbox.MHMessage,
1003 mailbox.BabylMessage, mailbox.MMDFMessage):
1004 other_msg = class_()
1005 msg._explain_to(other_msg)
Thomas Woutersb2137042007-02-01 18:02:27 +00001006 other_msg = email.message.Message()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001007 self.assertRaises(TypeError, lambda: msg._explain_to(other_msg))
1008
1009 def _post_initialize_hook(self, msg):
1010 # Overridden by subclasses to check extra things after initialization
1011 pass
1012
1013
1014class TestMaildirMessage(TestMessage):
1015
1016 _factory = mailbox.MaildirMessage
1017
1018 def _post_initialize_hook(self, msg):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001019 self.assertEqual(msg._subdir, 'new')
1020 self.assertEqual(msg._info, '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001021
1022 def test_subdir(self):
1023 # Use get_subdir() and set_subdir()
1024 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001025 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001026 msg.set_subdir('cur')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001027 self.assertEqual(msg.get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001028 msg.set_subdir('new')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001029 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001030 self.assertRaises(ValueError, lambda: msg.set_subdir('tmp'))
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001031 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001032 msg.set_subdir('new')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001033 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001034 self._check_sample(msg)
1035
1036 def test_flags(self):
1037 # Use get_flags(), set_flags(), add_flag(), remove_flag()
1038 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001039 self.assertEqual(msg.get_flags(), '')
1040 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041 msg.set_flags('F')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001042 self.assertEqual(msg.get_subdir(), 'new')
1043 self.assertEqual(msg.get_flags(), 'F')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001044 msg.set_flags('SDTP')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001045 self.assertEqual(msg.get_flags(), 'DPST')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001046 msg.add_flag('FT')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001047 self.assertEqual(msg.get_flags(), 'DFPST')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001048 msg.remove_flag('TDRP')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001049 self.assertEqual(msg.get_flags(), 'FS')
1050 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001051 self._check_sample(msg)
1052
1053 def test_date(self):
1054 # Use get_date() and set_date()
1055 msg = mailbox.MaildirMessage(_sample_message)
1056 self.assert_(abs(msg.get_date() - time.time()) < 60)
1057 msg.set_date(0.0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001058 self.assertEqual(msg.get_date(), 0.0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001059
1060 def test_info(self):
1061 # Use get_info() and set_info()
1062 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001063 self.assertEqual(msg.get_info(), '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001064 msg.set_info('1,foo=bar')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001065 self.assertEqual(msg.get_info(), '1,foo=bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001066 self.assertRaises(TypeError, lambda: msg.set_info(None))
1067 self._check_sample(msg)
1068
1069 def test_info_and_flags(self):
1070 # Test interaction of info and flag methods
1071 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001072 self.assertEqual(msg.get_info(), '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073 msg.set_flags('SF')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001074 self.assertEqual(msg.get_flags(), 'FS')
1075 self.assertEqual(msg.get_info(), '2,FS')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001076 msg.set_info('1,')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001077 self.assertEqual(msg.get_flags(), '')
1078 self.assertEqual(msg.get_info(), '1,')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001079 msg.remove_flag('RPT')
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.add_flag('D')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001083 self.assertEqual(msg.get_flags(), 'D')
1084 self.assertEqual(msg.get_info(), '2,D')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001085 self._check_sample(msg)
1086
1087
1088class _TestMboxMMDFMessage(TestMessage):
1089
1090 _factory = mailbox._mboxMMDFMessage
1091
1092 def _post_initialize_hook(self, msg):
1093 self._check_from(msg)
1094
1095 def test_initialize_with_unixfrom(self):
1096 # Initialize with a message that already has a _unixfrom attribute
1097 msg = mailbox.Message(_sample_message)
1098 msg.set_unixfrom('From foo@bar blah')
1099 msg = mailbox.mboxMessage(msg)
Guido van Rossumea834472007-07-27 05:17:50 +00001100 self.assertEqual(msg.get_from(), 'foo@bar blah', msg.get_from())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001101
1102 def test_from(self):
1103 # Get and set "From " line
1104 msg = mailbox.mboxMessage(_sample_message)
1105 self._check_from(msg)
1106 msg.set_from('foo bar')
Guido van Rossumea834472007-07-27 05:17:50 +00001107 self.assertEqual(msg.get_from(), 'foo bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001108 msg.set_from('foo@bar', True)
1109 self._check_from(msg, 'foo@bar')
1110 msg.set_from('blah@temp', time.localtime())
1111 self._check_from(msg, 'blah@temp')
1112
1113 def test_flags(self):
1114 # Use get_flags(), set_flags(), add_flag(), remove_flag()
1115 msg = mailbox.mboxMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001116 self.assertEqual(msg.get_flags(), '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001117 msg.set_flags('F')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001118 self.assertEqual(msg.get_flags(), 'F')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001119 msg.set_flags('XODR')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001120 self.assertEqual(msg.get_flags(), 'RODX')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001121 msg.add_flag('FA')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001122 self.assertEqual(msg.get_flags(), 'RODFAX')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123 msg.remove_flag('FDXA')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001124 self.assertEqual(msg.get_flags(), 'RO')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001125 self._check_sample(msg)
1126
1127 def _check_from(self, msg, sender=None):
1128 # Check contents of "From " line
1129 if sender is None:
1130 sender = "MAILER-DAEMON"
1131 self.assert_(re.match(sender + r" \w{3} \w{3} [\d ]\d [\d ]\d:\d{2}:"
1132 r"\d{2} \d{4}", msg.get_from()) is not None)
1133
1134
1135class TestMboxMessage(_TestMboxMMDFMessage):
1136
1137 _factory = mailbox.mboxMessage
1138
1139
1140class TestMHMessage(TestMessage):
1141
1142 _factory = mailbox.MHMessage
1143
1144 def _post_initialize_hook(self, msg):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001145 self.assertEqual(msg._sequences, [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001146
1147 def test_sequences(self):
1148 # Get, set, join, and leave sequences
1149 msg = mailbox.MHMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001150 self.assertEqual(msg.get_sequences(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001151 msg.set_sequences(['foobar'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001152 self.assertEqual(msg.get_sequences(), ['foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001153 msg.set_sequences([])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001154 self.assertEqual(msg.get_sequences(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001155 msg.add_sequence('unseen')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001156 self.assertEqual(msg.get_sequences(), ['unseen'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001157 msg.add_sequence('flagged')
Guido van Rossumea834472007-07-27 05:17:50 +00001158 self.assertEqual(msg.get_sequences(), ['unseen', 'flagged'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001159 msg.add_sequence('flagged')
Guido van Rossumea834472007-07-27 05:17:50 +00001160 self.assertEqual(msg.get_sequences(), ['unseen', 'flagged'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001161 msg.remove_sequence('unseen')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001162 self.assertEqual(msg.get_sequences(), ['flagged'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001163 msg.add_sequence('foobar')
Guido van Rossumea834472007-07-27 05:17:50 +00001164 self.assertEqual(msg.get_sequences(), ['flagged', 'foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001165 msg.remove_sequence('replied')
Guido van Rossumea834472007-07-27 05:17:50 +00001166 self.assertEqual(msg.get_sequences(), ['flagged', 'foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001167 msg.set_sequences(['foobar', 'replied'])
Guido van Rossumea834472007-07-27 05:17:50 +00001168 self.assertEqual(msg.get_sequences(), ['foobar', 'replied'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001169
1170
1171class TestBabylMessage(TestMessage):
1172
1173 _factory = mailbox.BabylMessage
1174
1175 def _post_initialize_hook(self, msg):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001176 self.assertEqual(msg._labels, [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001177
1178 def test_labels(self):
1179 # Get, set, join, and leave labels
1180 msg = mailbox.BabylMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001181 self.assertEqual(msg.get_labels(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001182 msg.set_labels(['foobar'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001183 self.assertEqual(msg.get_labels(), ['foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001184 msg.set_labels([])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001185 self.assertEqual(msg.get_labels(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001186 msg.add_label('filed')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001187 self.assertEqual(msg.get_labels(), ['filed'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001188 msg.add_label('resent')
Guido van Rossumea834472007-07-27 05:17:50 +00001189 self.assertEqual(msg.get_labels(), ['filed', 'resent'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001190 msg.add_label('resent')
Guido van Rossumea834472007-07-27 05:17:50 +00001191 self.assertEqual(msg.get_labels(), ['filed', 'resent'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001192 msg.remove_label('filed')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001193 self.assertEqual(msg.get_labels(), ['resent'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001194 msg.add_label('foobar')
Guido van Rossumea834472007-07-27 05:17:50 +00001195 self.assertEqual(msg.get_labels(), ['resent', 'foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001196 msg.remove_label('unseen')
Guido van Rossumea834472007-07-27 05:17:50 +00001197 self.assertEqual(msg.get_labels(), ['resent', 'foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001198 msg.set_labels(['foobar', 'answered'])
Guido van Rossumea834472007-07-27 05:17:50 +00001199 self.assertEqual(msg.get_labels(), ['foobar', 'answered'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001200
1201 def test_visible(self):
1202 # Get, set, and update visible headers
1203 msg = mailbox.BabylMessage(_sample_message)
1204 visible = msg.get_visible()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001205 self.assertEqual(visible.keys(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001206 self.assert_(visible.get_payload() is None)
1207 visible['User-Agent'] = 'FooBar 1.0'
1208 visible['X-Whatever'] = 'Blah'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001209 self.assertEqual(msg.get_visible().keys(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001210 msg.set_visible(visible)
1211 visible = msg.get_visible()
1212 self.assert_(visible.keys() == ['User-Agent', 'X-Whatever'])
1213 self.assert_(visible['User-Agent'] == 'FooBar 1.0')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001214 self.assertEqual(visible['X-Whatever'], 'Blah')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001215 self.assert_(visible.get_payload() is None)
1216 msg.update_visible()
Guido van Rossumea834472007-07-27 05:17:50 +00001217 self.assertEqual(visible.keys(), ['User-Agent', 'X-Whatever'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001218 self.assert_(visible.get_payload() is None)
1219 visible = msg.get_visible()
Guido van Rossumea834472007-07-27 05:17:50 +00001220 self.assertEqual(visible.keys(), ['User-Agent', 'Date', 'From', 'To',
1221 'Subject'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001222 for header in ('User-Agent', 'Date', 'From', 'To', 'Subject'):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001223 self.assertEqual(visible[header], msg[header])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001224
1225
1226class TestMMDFMessage(_TestMboxMMDFMessage):
1227
1228 _factory = mailbox.MMDFMessage
1229
1230
1231class TestMessageConversion(TestBase):
1232
1233 def test_plain_to_x(self):
1234 # Convert Message to all formats
1235 for class_ in (mailbox.Message, mailbox.MaildirMessage,
1236 mailbox.mboxMessage, mailbox.MHMessage,
1237 mailbox.BabylMessage, mailbox.MMDFMessage):
1238 msg_plain = mailbox.Message(_sample_message)
1239 msg = class_(msg_plain)
1240 self._check_sample(msg)
1241
1242 def test_x_to_plain(self):
1243 # Convert all formats to Message
1244 for class_ in (mailbox.Message, mailbox.MaildirMessage,
1245 mailbox.mboxMessage, mailbox.MHMessage,
1246 mailbox.BabylMessage, mailbox.MMDFMessage):
1247 msg = class_(_sample_message)
1248 msg_plain = mailbox.Message(msg)
1249 self._check_sample(msg_plain)
1250
1251 def test_x_to_invalid(self):
1252 # Convert all formats to an invalid format
1253 for class_ in (mailbox.Message, mailbox.MaildirMessage,
1254 mailbox.mboxMessage, mailbox.MHMessage,
1255 mailbox.BabylMessage, mailbox.MMDFMessage):
1256 self.assertRaises(TypeError, lambda: class_(False))
1257
1258 def test_maildir_to_maildir(self):
1259 # Convert MaildirMessage to MaildirMessage
1260 msg_maildir = mailbox.MaildirMessage(_sample_message)
1261 msg_maildir.set_flags('DFPRST')
1262 msg_maildir.set_subdir('cur')
1263 date = msg_maildir.get_date()
1264 msg = mailbox.MaildirMessage(msg_maildir)
1265 self._check_sample(msg)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001266 self.assertEqual(msg.get_flags(), 'DFPRST')
1267 self.assertEqual(msg.get_subdir(), 'cur')
1268 self.assertEqual(msg.get_date(), date)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001269
1270 def test_maildir_to_mboxmmdf(self):
1271 # Convert MaildirMessage to mboxmessage and MMDFMessage
1272 pairs = (('D', ''), ('F', 'F'), ('P', ''), ('R', 'A'), ('S', 'R'),
1273 ('T', 'D'), ('DFPRST', 'RDFA'))
1274 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1275 msg_maildir = mailbox.MaildirMessage(_sample_message)
1276 msg_maildir.set_date(0.0)
1277 for setting, result in pairs:
1278 msg_maildir.set_flags(setting)
1279 msg = class_(msg_maildir)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001280 self.assertEqual(msg.get_flags(), result)
Guido van Rossumea834472007-07-27 05:17:50 +00001281 self.assertEqual(msg.get_from(), 'MAILER-DAEMON %s' %
Thomas Wouters477c8d52006-05-27 19:21:47 +00001282 time.asctime(time.gmtime(0.0)))
1283 msg_maildir.set_subdir('cur')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001284 self.assertEqual(class_(msg_maildir).get_flags(), 'RODFA')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001285
1286 def test_maildir_to_mh(self):
1287 # Convert MaildirMessage to MHMessage
1288 msg_maildir = mailbox.MaildirMessage(_sample_message)
1289 pairs = (('D', ['unseen']), ('F', ['unseen', 'flagged']),
1290 ('P', ['unseen']), ('R', ['unseen', 'replied']), ('S', []),
1291 ('T', ['unseen']), ('DFPRST', ['replied', 'flagged']))
1292 for setting, result in pairs:
1293 msg_maildir.set_flags(setting)
Guido van Rossumea834472007-07-27 05:17:50 +00001294 self.assertEqual(mailbox.MHMessage(msg_maildir).get_sequences(),
1295 result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001296
1297 def test_maildir_to_babyl(self):
1298 # Convert MaildirMessage to Babyl
1299 msg_maildir = mailbox.MaildirMessage(_sample_message)
1300 pairs = (('D', ['unseen']), ('F', ['unseen']),
1301 ('P', ['unseen', 'forwarded']), ('R', ['unseen', 'answered']),
1302 ('S', []), ('T', ['unseen', 'deleted']),
1303 ('DFPRST', ['deleted', 'answered', 'forwarded']))
1304 for setting, result in pairs:
1305 msg_maildir.set_flags(setting)
Guido van Rossumea834472007-07-27 05:17:50 +00001306 self.assertEqual(mailbox.BabylMessage(msg_maildir).get_labels(),
1307 result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001308
1309 def test_mboxmmdf_to_maildir(self):
1310 # Convert mboxMessage and MMDFMessage to MaildirMessage
1311 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1312 msg_mboxMMDF = class_(_sample_message)
1313 msg_mboxMMDF.set_from('foo@bar', time.gmtime(0.0))
1314 pairs = (('R', 'S'), ('O', ''), ('D', 'T'), ('F', 'F'), ('A', 'R'),
1315 ('RODFA', 'FRST'))
1316 for setting, result in pairs:
1317 msg_mboxMMDF.set_flags(setting)
1318 msg = mailbox.MaildirMessage(msg_mboxMMDF)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001319 self.assertEqual(msg.get_flags(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001320 self.assert_(msg.get_date() == 0.0, msg.get_date())
1321 msg_mboxMMDF.set_flags('O')
Guido van Rossumea834472007-07-27 05:17:50 +00001322 self.assertEqual(mailbox.MaildirMessage(msg_mboxMMDF).get_subdir(),
1323 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001324
1325 def test_mboxmmdf_to_mboxmmdf(self):
1326 # Convert mboxMessage and MMDFMessage to mboxMessage and MMDFMessage
1327 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1328 msg_mboxMMDF = class_(_sample_message)
1329 msg_mboxMMDF.set_flags('RODFA')
1330 msg_mboxMMDF.set_from('foo@bar')
1331 for class2_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1332 msg2 = class2_(msg_mboxMMDF)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001333 self.assertEqual(msg2.get_flags(), 'RODFA')
1334 self.assertEqual(msg2.get_from(), 'foo@bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001335
1336 def test_mboxmmdf_to_mh(self):
1337 # Convert mboxMessage and MMDFMessage to MHMessage
1338 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1339 msg_mboxMMDF = class_(_sample_message)
1340 pairs = (('R', []), ('O', ['unseen']), ('D', ['unseen']),
1341 ('F', ['unseen', 'flagged']),
1342 ('A', ['unseen', 'replied']),
1343 ('RODFA', ['replied', 'flagged']))
1344 for setting, result in pairs:
1345 msg_mboxMMDF.set_flags(setting)
Guido van Rossumea834472007-07-27 05:17:50 +00001346 self.assertEqual(mailbox.MHMessage(msg_mboxMMDF).get_sequences(),
1347 result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001348
1349 def test_mboxmmdf_to_babyl(self):
1350 # Convert mboxMessage and MMDFMessage to BabylMessage
1351 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1352 msg = class_(_sample_message)
1353 pairs = (('R', []), ('O', ['unseen']),
1354 ('D', ['unseen', 'deleted']), ('F', ['unseen']),
1355 ('A', ['unseen', 'answered']),
1356 ('RODFA', ['deleted', 'answered']))
1357 for setting, result in pairs:
1358 msg.set_flags(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001359 self.assertEqual(mailbox.BabylMessage(msg).get_labels(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001360
1361 def test_mh_to_maildir(self):
1362 # Convert MHMessage to MaildirMessage
1363 pairs = (('unseen', ''), ('replied', 'RS'), ('flagged', 'FS'))
1364 for setting, result in pairs:
1365 msg = mailbox.MHMessage(_sample_message)
1366 msg.add_sequence(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001367 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), result)
1368 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001369 msg = mailbox.MHMessage(_sample_message)
1370 msg.add_sequence('unseen')
1371 msg.add_sequence('replied')
1372 msg.add_sequence('flagged')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001373 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), 'FR')
1374 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001375
1376 def test_mh_to_mboxmmdf(self):
1377 # Convert MHMessage to mboxMessage and MMDFMessage
1378 pairs = (('unseen', 'O'), ('replied', 'ROA'), ('flagged', 'ROF'))
1379 for setting, result in pairs:
1380 msg = mailbox.MHMessage(_sample_message)
1381 msg.add_sequence(setting)
1382 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001383 self.assertEqual(class_(msg).get_flags(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001384 msg = mailbox.MHMessage(_sample_message)
1385 msg.add_sequence('unseen')
1386 msg.add_sequence('replied')
1387 msg.add_sequence('flagged')
1388 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001389 self.assertEqual(class_(msg).get_flags(), 'OFA')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001390
1391 def test_mh_to_mh(self):
1392 # Convert MHMessage to MHMessage
1393 msg = mailbox.MHMessage(_sample_message)
1394 msg.add_sequence('unseen')
1395 msg.add_sequence('replied')
1396 msg.add_sequence('flagged')
Guido van Rossumea834472007-07-27 05:17:50 +00001397 self.assertEqual(mailbox.MHMessage(msg).get_sequences(),
1398 ['unseen', 'replied', 'flagged'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001399
1400 def test_mh_to_babyl(self):
1401 # Convert MHMessage to BabylMessage
1402 pairs = (('unseen', ['unseen']), ('replied', ['answered']),
1403 ('flagged', []))
1404 for setting, result in pairs:
1405 msg = mailbox.MHMessage(_sample_message)
1406 msg.add_sequence(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001407 self.assertEqual(mailbox.BabylMessage(msg).get_labels(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001408 msg = mailbox.MHMessage(_sample_message)
1409 msg.add_sequence('unseen')
1410 msg.add_sequence('replied')
1411 msg.add_sequence('flagged')
Guido van Rossumea834472007-07-27 05:17:50 +00001412 self.assertEqual(mailbox.BabylMessage(msg).get_labels(),
1413 ['unseen', 'answered'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001414
1415 def test_babyl_to_maildir(self):
1416 # Convert BabylMessage to MaildirMessage
1417 pairs = (('unseen', ''), ('deleted', 'ST'), ('filed', 'S'),
1418 ('answered', 'RS'), ('forwarded', 'PS'), ('edited', 'S'),
1419 ('resent', 'PS'))
1420 for setting, result in pairs:
1421 msg = mailbox.BabylMessage(_sample_message)
1422 msg.add_label(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001423 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), result)
1424 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001425 msg = mailbox.BabylMessage(_sample_message)
1426 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1427 'edited', 'resent'):
1428 msg.add_label(label)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001429 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), 'PRT')
1430 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001431
1432 def test_babyl_to_mboxmmdf(self):
1433 # Convert BabylMessage to mboxMessage and MMDFMessage
1434 pairs = (('unseen', 'O'), ('deleted', 'ROD'), ('filed', 'RO'),
1435 ('answered', 'ROA'), ('forwarded', 'RO'), ('edited', 'RO'),
1436 ('resent', 'RO'))
1437 for setting, result in pairs:
1438 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1439 msg = mailbox.BabylMessage(_sample_message)
1440 msg.add_label(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001441 self.assertEqual(class_(msg).get_flags(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001442 msg = mailbox.BabylMessage(_sample_message)
1443 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1444 'edited', 'resent'):
1445 msg.add_label(label)
1446 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001447 self.assertEqual(class_(msg).get_flags(), 'ODA')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001448
1449 def test_babyl_to_mh(self):
1450 # Convert BabylMessage to MHMessage
1451 pairs = (('unseen', ['unseen']), ('deleted', []), ('filed', []),
1452 ('answered', ['replied']), ('forwarded', []), ('edited', []),
1453 ('resent', []))
1454 for setting, result in pairs:
1455 msg = mailbox.BabylMessage(_sample_message)
1456 msg.add_label(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001457 self.assertEqual(mailbox.MHMessage(msg).get_sequences(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001458 msg = mailbox.BabylMessage(_sample_message)
1459 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1460 'edited', 'resent'):
1461 msg.add_label(label)
Guido van Rossumea834472007-07-27 05:17:50 +00001462 self.assertEqual(mailbox.MHMessage(msg).get_sequences(),
1463 ['unseen', 'replied'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001464
1465 def test_babyl_to_babyl(self):
1466 # Convert BabylMessage to BabylMessage
1467 msg = mailbox.BabylMessage(_sample_message)
1468 msg.update_visible()
1469 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1470 'edited', 'resent'):
1471 msg.add_label(label)
1472 msg2 = mailbox.BabylMessage(msg)
Guido van Rossumea834472007-07-27 05:17:50 +00001473 self.assertEqual(msg2.get_labels(), ['unseen', 'deleted', 'filed',
1474 'answered', 'forwarded', 'edited',
1475 'resent'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001476 self.assertEqual(msg.get_visible().keys(), msg2.get_visible().keys())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001477 for key in msg.get_visible().keys():
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001478 self.assertEqual(msg.get_visible()[key], msg2.get_visible()[key])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001479
1480
1481class TestProxyFileBase(TestBase):
1482
1483 def _test_read(self, proxy):
1484 # Read by byte
1485 proxy.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001486 self.assertEqual(proxy.read(), 'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001487 proxy.seek(1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001488 self.assertEqual(proxy.read(), 'ar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001489 proxy.seek(0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001490 self.assertEqual(proxy.read(2), 'ba')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001491 proxy.seek(1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001492 self.assertEqual(proxy.read(-1), 'ar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001493 proxy.seek(2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001494 self.assertEqual(proxy.read(1000), 'r')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001495
1496 def _test_readline(self, proxy):
1497 # Read by line
1498 proxy.seek(0)
Guido van Rossumea834472007-07-27 05:17:50 +00001499 self.assertEqual(proxy.readline(), 'foo' + os.linesep)
1500 self.assertEqual(proxy.readline(), 'bar' + os.linesep)
1501 self.assertEqual(proxy.readline(), 'fred' + os.linesep)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001502 self.assertEqual(proxy.readline(), 'bob')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001503 proxy.seek(2)
Guido van Rossumea834472007-07-27 05:17:50 +00001504 self.assertEqual(proxy.readline(), 'o' + os.linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001505 proxy.seek(6 + 2 * len(os.linesep))
Guido van Rossumea834472007-07-27 05:17:50 +00001506 self.assertEqual(proxy.readline(), 'fred' + os.linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001507 proxy.seek(6 + 2 * len(os.linesep))
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001508 self.assertEqual(proxy.readline(2), 'fr')
Guido van Rossumea834472007-07-27 05:17:50 +00001509 self.assertEqual(proxy.readline(-10), 'ed' + os.linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001510
1511 def _test_readlines(self, proxy):
1512 # Read multiple lines
1513 proxy.seek(0)
Guido van Rossumea834472007-07-27 05:17:50 +00001514 self.assertEqual(proxy.readlines(), ['foo' + os.linesep,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001515 'bar' + os.linesep,
1516 'fred' + os.linesep, 'bob'])
1517 proxy.seek(0)
Guido van Rossumea834472007-07-27 05:17:50 +00001518 self.assertEqual(proxy.readlines(2), ['foo' + os.linesep])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001519 proxy.seek(3 + len(os.linesep))
Guido van Rossumea834472007-07-27 05:17:50 +00001520 self.assertEqual(proxy.readlines(4 + len(os.linesep)),
Thomas Wouters477c8d52006-05-27 19:21:47 +00001521 ['bar' + os.linesep, 'fred' + os.linesep])
1522 proxy.seek(3)
Guido van Rossumea834472007-07-27 05:17:50 +00001523 self.assertEqual(proxy.readlines(1000), [os.linesep, 'bar' + os.linesep,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001524 'fred' + os.linesep, 'bob'])
1525
1526 def _test_iteration(self, proxy):
1527 # Iterate by line
1528 proxy.seek(0)
1529 iterator = iter(proxy)
Guido van Rossumea834472007-07-27 05:17:50 +00001530 self.assertEqual(next(iterator), 'foo' + os.linesep)
1531 self.assertEqual(next(iterator), 'bar' + os.linesep)
1532 self.assertEqual(next(iterator), 'fred' + os.linesep)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001533 self.assertEqual(next(iterator), 'bob')
Georg Brandla18af4e2007-04-21 15:47:16 +00001534 self.assertRaises(StopIteration, next, iterator)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001535
1536 def _test_seek_and_tell(self, proxy):
1537 # Seek and use tell to check position
1538 proxy.seek(3)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001539 self.assertEqual(proxy.tell(), 3)
1540 self.assertEqual(proxy.read(len(os.linesep)), os.linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001541 proxy.seek(2, 1)
Guido van Rossumea834472007-07-27 05:17:50 +00001542 self.assertEqual(proxy.read(1 + len(os.linesep)), 'r' + os.linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001543 proxy.seek(-3 - len(os.linesep), 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001544 self.assertEqual(proxy.read(3), 'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001545 proxy.seek(2, 0)
Guido van Rossumea834472007-07-27 05:17:50 +00001546 self.assertEqual(proxy.read(), 'o' + os.linesep + 'bar' + os.linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001547 proxy.seek(100)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001548 self.assertEqual(proxy.read(), '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001549
1550 def _test_close(self, proxy):
1551 # Close a file
1552 proxy.close()
1553 self.assertRaises(AttributeError, lambda: proxy.close())
1554
1555
1556class TestProxyFile(TestProxyFileBase):
1557
1558 def setUp(self):
1559 self._path = test_support.TESTFN
1560 self._file = open(self._path, 'wb+')
1561
1562 def tearDown(self):
1563 self._file.close()
1564 self._delete_recursively(self._path)
1565
1566 def test_initialize(self):
1567 # Initialize and check position
Neal Norwitz9a923102007-08-30 06:20:05 +00001568 self._file.write(b'foo')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001569 pos = self._file.tell()
1570 proxy0 = mailbox._ProxyFile(self._file)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001571 self.assertEqual(proxy0.tell(), pos)
1572 self.assertEqual(self._file.tell(), pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001573 proxy1 = mailbox._ProxyFile(self._file, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001574 self.assertEqual(proxy1.tell(), 0)
1575 self.assertEqual(self._file.tell(), pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001576
1577 def test_read(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001578 self._file.write(b'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001579 self._test_read(mailbox._ProxyFile(self._file))
1580
1581 def test_readline(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001582 self._file.write(bytes('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
1583 os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584 self._test_readline(mailbox._ProxyFile(self._file))
1585
1586 def test_readlines(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001587 self._file.write(bytes('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
1588 os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001589 self._test_readlines(mailbox._ProxyFile(self._file))
1590
1591 def test_iteration(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001592 self._file.write(bytes('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
1593 os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001594 self._test_iteration(mailbox._ProxyFile(self._file))
1595
1596 def test_seek_and_tell(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001597 self._file.write(bytes('foo%sbar%s' % (os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001598 self._test_seek_and_tell(mailbox._ProxyFile(self._file))
1599
1600 def test_close(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001601 self._file.write(bytes('foo%sbar%s' % (os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001602 self._test_close(mailbox._ProxyFile(self._file))
1603
1604
1605class TestPartialFile(TestProxyFileBase):
1606
1607 def setUp(self):
1608 self._path = test_support.TESTFN
1609 self._file = open(self._path, 'wb+')
1610
1611 def tearDown(self):
1612 self._file.close()
1613 self._delete_recursively(self._path)
1614
1615 def test_initialize(self):
1616 # Initialize and check position
Neal Norwitz9a923102007-08-30 06:20:05 +00001617 self._file.write(bytes('foo' + os.linesep + 'bar', 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001618 pos = self._file.tell()
1619 proxy = mailbox._PartialFile(self._file, 2, 5)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001620 self.assertEqual(proxy.tell(), 0)
1621 self.assertEqual(self._file.tell(), pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001622
1623 def test_read(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001624 self._file.write(bytes('***bar***', 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001625 self._test_read(mailbox._PartialFile(self._file, 3, 6))
1626
1627 def test_readline(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001628 self._file.write(bytes('!!!!!foo%sbar%sfred%sbob!!!!!' %
1629 (os.linesep, os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001630 self._test_readline(mailbox._PartialFile(self._file, 5,
1631 18 + 3 * len(os.linesep)))
1632
1633 def test_readlines(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001634 self._file.write(bytes('foo%sbar%sfred%sbob?????' %
1635 (os.linesep, os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001636 self._test_readlines(mailbox._PartialFile(self._file, 0,
1637 13 + 3 * len(os.linesep)))
1638
1639 def test_iteration(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001640 self._file.write(bytes('____foo%sbar%sfred%sbob####' %
1641 (os.linesep, os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001642 self._test_iteration(mailbox._PartialFile(self._file, 4,
1643 17 + 3 * len(os.linesep)))
1644
1645 def test_seek_and_tell(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001646 self._file.write(bytes('(((foo%sbar%s$$$' % (os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001647 self._test_seek_and_tell(mailbox._PartialFile(self._file, 3,
1648 9 + 2 * len(os.linesep)))
1649
1650 def test_close(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00001651 self._file.write(bytes('&foo%sbar%s^' % (os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001652 self._test_close(mailbox._PartialFile(self._file, 1,
1653 6 + 3 * len(os.linesep)))
1654
1655
1656## Start: tests from the original module (for backward compatibility).
1657
Skip Montanaro5253da12004-07-24 19:56:03 +00001658FROM_ = "From some.body@dummy.domain Sat Jul 24 13:43:35 2004\n"
Fred Drakec02bc3e2001-05-21 20:23:21 +00001659DUMMY_MESSAGE = """\
1660From: some.body@dummy.domain
1661To: me@my.domain
Skip Montanaro5253da12004-07-24 19:56:03 +00001662Subject: Simple Test
Fred Drakec02bc3e2001-05-21 20:23:21 +00001663
1664This is a dummy message.
1665"""
1666
Fred Drakec02bc3e2001-05-21 20:23:21 +00001667class MaildirTestCase(unittest.TestCase):
1668
1669 def setUp(self):
1670 # create a new maildir mailbox to work with:
1671 self._dir = test_support.TESTFN
1672 os.mkdir(self._dir)
1673 os.mkdir(os.path.join(self._dir, "cur"))
1674 os.mkdir(os.path.join(self._dir, "tmp"))
1675 os.mkdir(os.path.join(self._dir, "new"))
1676 self._counter = 1
1677 self._msgfiles = []
1678
1679 def tearDown(self):
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001680 list(map(os.unlink, self._msgfiles))
Fred Drakec02bc3e2001-05-21 20:23:21 +00001681 os.rmdir(os.path.join(self._dir, "cur"))
1682 os.rmdir(os.path.join(self._dir, "tmp"))
1683 os.rmdir(os.path.join(self._dir, "new"))
1684 os.rmdir(self._dir)
1685
Skip Montanaro5253da12004-07-24 19:56:03 +00001686 def createMessage(self, dir, mbox=False):
Jack Jansen97df7b62001-06-19 20:20:05 +00001687 t = int(time.time() % 1000000)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001688 pid = self._counter
1689 self._counter += 1
Skip Montanaro7a98be22007-08-16 14:35:24 +00001690 filename = ".".join((str(t), str(pid), "myhostname", "mydomain"))
Fred Drakec02bc3e2001-05-21 20:23:21 +00001691 tmpname = os.path.join(self._dir, "tmp", filename)
1692 newname = os.path.join(self._dir, dir, filename)
1693 fp = open(tmpname, "w")
1694 self._msgfiles.append(tmpname)
Skip Montanaro5253da12004-07-24 19:56:03 +00001695 if mbox:
1696 fp.write(FROM_)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001697 fp.write(DUMMY_MESSAGE)
1698 fp.close()
Tim Peters6626c1f2001-05-22 16:29:01 +00001699 if hasattr(os, "link"):
1700 os.link(tmpname, newname)
1701 else:
1702 fp = open(newname, "w")
1703 fp.write(DUMMY_MESSAGE)
1704 fp.close()
Fred Drakec02bc3e2001-05-21 20:23:21 +00001705 self._msgfiles.append(newname)
Skip Montanaro5253da12004-07-24 19:56:03 +00001706 return tmpname
Fred Drakec02bc3e2001-05-21 20:23:21 +00001707
1708 def test_empty_maildir(self):
1709 """Test an empty maildir mailbox"""
1710 # Test for regression on bug #117490:
1711 # Make sure the boxes attribute actually gets set.
1712 self.mbox = mailbox.Maildir(test_support.TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001713 #self.assert_(hasattr(self.mbox, "boxes"))
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001714 #self.assertEqual(len(self.mbox.boxes), 0)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001715 self.assert_(self.mbox.next() is None)
1716 self.assert_(self.mbox.next() is None)
1717
1718 def test_nonempty_maildir_cur(self):
1719 self.createMessage("cur")
1720 self.mbox = mailbox.Maildir(test_support.TESTFN)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001721 #self.assertEqual(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_new(self):
1727 self.createMessage("new")
1728 self.mbox = mailbox.Maildir(test_support.TESTFN)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001729 #self.assertEqual(len(self.mbox.boxes), 1)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001730 self.assert_(self.mbox.next() is not None)
1731 self.assert_(self.mbox.next() is None)
1732 self.assert_(self.mbox.next() is None)
1733
1734 def test_nonempty_maildir_both(self):
1735 self.createMessage("cur")
1736 self.createMessage("new")
1737 self.mbox = mailbox.Maildir(test_support.TESTFN)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001738 #self.assertEqual(len(self.mbox.boxes), 2)
Fred Drakec02bc3e2001-05-21 20:23:21 +00001739 self.assert_(self.mbox.next() is not None)
1740 self.assert_(self.mbox.next() is not None)
1741 self.assert_(self.mbox.next() is None)
1742 self.assert_(self.mbox.next() is None)
Fred Drake0aaed272000-10-23 13:39:15 +00001743
Skip Montanaro5253da12004-07-24 19:56:03 +00001744 def test_unix_mbox(self):
1745 ### should be better!
Thomas Woutersb2137042007-02-01 18:02:27 +00001746 import email.parser
Skip Montanaro5253da12004-07-24 19:56:03 +00001747 fname = self.createMessage("cur", True)
1748 n = 0
1749 for msg in mailbox.PortableUnixMailbox(open(fname),
Thomas Woutersb2137042007-02-01 18:02:27 +00001750 email.parser.Parser().parse):
Skip Montanaro5253da12004-07-24 19:56:03 +00001751 n += 1
1752 self.assertEqual(msg["subject"], "Simple Test")
1753 self.assertEqual(len(str(msg)), len(FROM_)+len(DUMMY_MESSAGE))
1754 self.assertEqual(n, 1)
1755
Thomas Wouters477c8d52006-05-27 19:21:47 +00001756## End: classes from the original module (for backward compatibility).
1757
1758
1759_sample_message = """\
1760Return-Path: <gkj@gregorykjohnson.com>
1761X-Original-To: gkj+person@localhost
1762Delivered-To: gkj+person@localhost
1763Received: from localhost (localhost [127.0.0.1])
1764 by andy.gregorykjohnson.com (Postfix) with ESMTP id 356ED9DD17
1765 for <gkj+person@localhost>; Wed, 13 Jul 2005 17:23:16 -0400 (EDT)
1766Delivered-To: gkj@sundance.gregorykjohnson.com
1767Received: from localhost [127.0.0.1]
1768 by localhost with POP3 (fetchmail-6.2.5)
1769 for gkj+person@localhost (single-drop); Wed, 13 Jul 2005 17:23:16 -0400 (EDT)
1770Received: from andy.gregorykjohnson.com (andy.gregorykjohnson.com [64.32.235.228])
1771 by sundance.gregorykjohnson.com (Postfix) with ESMTP id 5B056316746
1772 for <gkj@gregorykjohnson.com>; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)
1773Received: by andy.gregorykjohnson.com (Postfix, from userid 1000)
1774 id 490CD9DD17; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)
1775Date: Wed, 13 Jul 2005 17:23:11 -0400
1776From: "Gregory K. Johnson" <gkj@gregorykjohnson.com>
1777To: gkj@gregorykjohnson.com
1778Subject: Sample message
1779Message-ID: <20050713212311.GC4701@andy.gregorykjohnson.com>
1780Mime-Version: 1.0
1781Content-Type: multipart/mixed; boundary="NMuMz9nt05w80d4+"
1782Content-Disposition: inline
1783User-Agent: Mutt/1.5.9i
1784
1785
1786--NMuMz9nt05w80d4+
1787Content-Type: text/plain; charset=us-ascii
1788Content-Disposition: inline
1789
1790This is a sample message.
1791
1792--
1793Gregory K. Johnson
1794
1795--NMuMz9nt05w80d4+
1796Content-Type: application/octet-stream
1797Content-Disposition: attachment; filename="text.gz"
1798Content-Transfer-Encoding: base64
1799
1800H4sICM2D1UIAA3RleHQAC8nILFYAokSFktSKEoW0zJxUPa7wzJIMhZLyfIWczLzUYj0uAHTs
18013FYlAAAA
1802
1803--NMuMz9nt05w80d4+--
1804"""
1805
1806_sample_headers = {
1807 "Return-Path":"<gkj@gregorykjohnson.com>",
1808 "X-Original-To":"gkj+person@localhost",
1809 "Delivered-To":"gkj+person@localhost",
1810 "Received":"""from localhost (localhost [127.0.0.1])
1811 by andy.gregorykjohnson.com (Postfix) with ESMTP id 356ED9DD17
1812 for <gkj+person@localhost>; Wed, 13 Jul 2005 17:23:16 -0400 (EDT)""",
1813 "Delivered-To":"gkj@sundance.gregorykjohnson.com",
1814 "Received":"""from localhost [127.0.0.1]
1815 by localhost with POP3 (fetchmail-6.2.5)
1816 for gkj+person@localhost (single-drop); Wed, 13 Jul 2005 17:23:16 -0400 (EDT)""",
1817 "Received":"""from andy.gregorykjohnson.com (andy.gregorykjohnson.com [64.32.235.228])
1818 by sundance.gregorykjohnson.com (Postfix) with ESMTP id 5B056316746
1819 for <gkj@gregorykjohnson.com>; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)""",
1820 "Received":"""by andy.gregorykjohnson.com (Postfix, from userid 1000)
1821 id 490CD9DD17; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)""",
1822 "Date":"Wed, 13 Jul 2005 17:23:11 -0400",
1823 "From":""""Gregory K. Johnson" <gkj@gregorykjohnson.com>""",
1824 "To":"gkj@gregorykjohnson.com",
1825 "Subject":"Sample message",
1826 "Mime-Version":"1.0",
1827 "Content-Type":"""multipart/mixed; boundary="NMuMz9nt05w80d4+\"""",
1828 "Content-Disposition":"inline",
1829 "User-Agent": "Mutt/1.5.9i" }
1830
1831_sample_payloads = ("""This is a sample message.
1832
1833--
1834Gregory K. Johnson
1835""",
1836"""H4sICM2D1UIAA3RleHQAC8nILFYAokSFktSKEoW0zJxUPa7wzJIMhZLyfIWczLzUYj0uAHTs
18373FYlAAAA
1838""")
Fred Drake0aaed272000-10-23 13:39:15 +00001839
Fred Drakec02bc3e2001-05-21 20:23:21 +00001840
Fred Drake2e2be372001-09-20 21:33:42 +00001841def test_main():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001842 tests = (TestMailboxSuperclass, TestMaildir, TestMbox, TestMMDF, TestMH,
1843 TestBabyl, TestMessage, TestMaildirMessage, TestMboxMessage,
1844 TestMHMessage, TestBabylMessage, TestMMDFMessage,
1845 TestMessageConversion, TestProxyFile, TestPartialFile,
1846 MaildirTestCase)
1847 test_support.run_unittest(*tests)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001848 test_support.reap_children()
Fred Drake2e2be372001-09-20 21:33:42 +00001849
1850
Thomas Wouters477c8d52006-05-27 19:21:47 +00001851if __name__ == '__main__':
Fred Drake2e2be372001-09-20 21:33:42 +00001852 test_main()