blob: d1cc92e2536d4e634c464eee71e03d0700035bfd [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 re
Guido van Rossum34d19282007-08-09 01:03:29 +00009import io
Vinay Sajipf9596182012-03-02 01:01:13 +000010import shutil
R. David Murrayb7deff12011-01-30 06:21:28 +000011import tempfile
Benjamin Petersonee8712c2008-05-20 21:35:26 +000012from test import support
Thomas Wouters477c8d52006-05-27 19:21:47 +000013import unittest
R. David Murrayb7deff12011-01-30 06:21:28 +000014import textwrap
Thomas Wouters477c8d52006-05-27 19:21:47 +000015import mailbox
16import glob
Guido van Rossum75ebb292001-04-10 15:01:20 +000017try:
Thomas Wouters477c8d52006-05-27 19:21:47 +000018 import fcntl
19except ImportError:
Guido van Rossum75ebb292001-04-10 15:01:20 +000020 pass
21
Thomas Wouters477c8d52006-05-27 19:21:47 +000022
R David Murray317c8d22012-04-08 16:46:18 -040023class TestBase:
Thomas Wouters477c8d52006-05-27 19:21:47 +000024
R David Murrayc988e242012-04-08 21:00:27 -040025 all_mailbox_types = (mailbox.Message, mailbox.MaildirMessage,
26 mailbox.mboxMessage, mailbox.MHMessage,
27 mailbox.BabylMessage, mailbox.MMDFMessage)
28
Thomas Wouters477c8d52006-05-27 19:21:47 +000029 def _check_sample(self, msg):
30 # Inspect a mailbox.Message representation of the sample message
Ezio Melottie9615932010-01-24 19:26:24 +000031 self.assertIsInstance(msg, email.message.Message)
32 self.assertIsInstance(msg, mailbox.Message)
Guido van Rossumcc2b0162007-02-11 06:12:03 +000033 for key, value in _sample_headers.items():
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +000034 self.assertIn(value, msg.get_all(key))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000035 self.assertTrue(msg.is_multipart())
Guido van Rossume61fd5b2007-07-11 12:20:59 +000036 self.assertEqual(len(msg.get_payload()), len(_sample_payloads))
Thomas Wouters477c8d52006-05-27 19:21:47 +000037 for i, payload in enumerate(_sample_payloads):
38 part = msg.get_payload(i)
Ezio Melottie9615932010-01-24 19:26:24 +000039 self.assertIsInstance(part, email.message.Message)
40 self.assertNotIsInstance(part, mailbox.Message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +000041 self.assertEqual(part.get_payload(), payload)
Thomas Wouters477c8d52006-05-27 19:21:47 +000042
43 def _delete_recursively(self, target):
44 # Delete a file or delete a directory recursively
45 if os.path.isdir(target):
Vinay Sajipf9596182012-03-02 01:01:13 +000046 shutil.rmtree(target)
Thomas Wouters477c8d52006-05-27 19:21:47 +000047 elif os.path.exists(target):
48 os.remove(target)
49
50
51class TestMailbox(TestBase):
52
R. David Murrayb7deff12011-01-30 06:21:28 +000053 maxDiff = None
54
Thomas Wouters477c8d52006-05-27 19:21:47 +000055 _factory = None # Overridden by subclasses to reuse tests
Petri Lehtinen46809192012-09-25 21:58:51 +030056 _template = 'From: foo\n\n%s\n'
Thomas Wouters477c8d52006-05-27 19:21:47 +000057
58 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000059 self._path = support.TESTFN
Guido van Rossumd8faa362007-04-27 19:54:29 +000060 self._delete_recursively(self._path)
Thomas Wouters477c8d52006-05-27 19:21:47 +000061 self._box = self._factory(self._path)
62
63 def tearDown(self):
Guido van Rossumc12a8132007-10-26 04:29:23 +000064 self._box.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +000065 self._delete_recursively(self._path)
66
67 def test_add(self):
68 # Add copies of a sample message
69 keys = []
70 keys.append(self._box.add(self._template % 0))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000071 self.assertEqual(len(self._box), 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +000072 keys.append(self._box.add(mailbox.Message(_sample_message)))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000073 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +000074 keys.append(self._box.add(email.message_from_string(_sample_message)))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000075 self.assertEqual(len(self._box), 3)
R. David Murrayb7deff12011-01-30 06:21:28 +000076 keys.append(self._box.add(io.BytesIO(_bytes_sample_message)))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000077 self.assertEqual(len(self._box), 4)
Thomas Wouters477c8d52006-05-27 19:21:47 +000078 keys.append(self._box.add(_sample_message))
Guido van Rossume61fd5b2007-07-11 12:20:59 +000079 self.assertEqual(len(self._box), 5)
R. David Murrayb7deff12011-01-30 06:21:28 +000080 keys.append(self._box.add(_bytes_sample_message))
81 self.assertEqual(len(self._box), 6)
82 with self.assertWarns(DeprecationWarning):
83 keys.append(self._box.add(
84 io.TextIOWrapper(io.BytesIO(_bytes_sample_message))))
85 self.assertEqual(len(self._box), 7)
Guido van Rossumea834472007-07-27 05:17:50 +000086 self.assertEqual(self._box.get_string(keys[0]), self._template % 0)
R. David Murrayb7deff12011-01-30 06:21:28 +000087 for i in (1, 2, 3, 4, 5, 6):
Thomas Wouters477c8d52006-05-27 19:21:47 +000088 self._check_sample(self._box[keys[i]])
89
R. David Murrayb7deff12011-01-30 06:21:28 +000090 _nonascii_msg = textwrap.dedent("""\
91 From: foo
92 Subject: Falinaptár házhozszállítással. Már rendeltél?
93
94 0
95 """)
96
97 def test_add_invalid_8bit_bytes_header(self):
Marc-André Lemburg8f36af72011-02-25 15:42:01 +000098 key = self._box.add(self._nonascii_msg.encode('latin-1'))
R. David Murrayb7deff12011-01-30 06:21:28 +000099 self.assertEqual(len(self._box), 1)
100 self.assertEqual(self._box.get_bytes(key),
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000101 self._nonascii_msg.encode('latin-1'))
R. David Murrayb7deff12011-01-30 06:21:28 +0000102
103 def test_invalid_nonascii_header_as_string(self):
104 subj = self._nonascii_msg.splitlines()[1]
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000105 key = self._box.add(subj.encode('latin-1'))
R. David Murrayb7deff12011-01-30 06:21:28 +0000106 self.assertEqual(self._box.get_string(key),
107 'Subject: =?unknown-8bit?b?RmFsaW5hcHThciBo4Xpob3pzeuFsbO104XNz'
108 'YWwuIE3hciByZW5kZWx06Ww/?=\n\n')
109
R. David Murrayfc141142011-02-11 22:47:17 +0000110 def test_add_nonascii_string_header_raises(self):
R. David Murrayb7deff12011-01-30 06:21:28 +0000111 with self.assertRaisesRegex(ValueError, "ASCII-only"):
112 self._box.add(self._nonascii_msg)
R. David Murrayfc141142011-02-11 22:47:17 +0000113 self._box.flush()
114 self.assertEqual(len(self._box), 0)
115 self.assertMailboxEmpty()
116
117 def test_add_that_raises_leaves_mailbox_empty(self):
R David Murray7441a7a2012-03-14 02:59:51 -0400118 def raiser(*args, **kw):
119 raise Exception("a fake error")
120 support.patch(self, email.generator.BytesGenerator, 'flatten', raiser)
121 with self.assertRaises(Exception):
R. David Murrayfc141142011-02-11 22:47:17 +0000122 self._box.add(email.message_from_string("From: Alphöso"))
123 self.assertEqual(len(self._box), 0)
124 self._box.close()
125 self.assertMailboxEmpty()
R. David Murrayb7deff12011-01-30 06:21:28 +0000126
127 _non_latin_bin_msg = textwrap.dedent("""\
128 From: foo@bar.com
129 To: báz
130 Subject: Maintenant je vous présente mon collègue, le pouf célèbre
131 \tJean de Baddie
132 Mime-Version: 1.0
133 Content-Type: text/plain; charset="utf-8"
134 Content-Transfer-Encoding: 8bit
135
136 Да, они летят.
137 """).encode('utf-8')
138
139 def test_add_8bit_body(self):
140 key = self._box.add(self._non_latin_bin_msg)
141 self.assertEqual(self._box.get_bytes(key),
142 self._non_latin_bin_msg)
143 with self._box.get_file(key) as f:
144 self.assertEqual(f.read(),
145 self._non_latin_bin_msg.replace(b'\n',
146 os.linesep.encode()))
147 self.assertEqual(self._box[key].get_payload(),
148 "Да, они летят.\n")
149
150 def test_add_binary_file(self):
151 with tempfile.TemporaryFile('wb+') as f:
152 f.write(_bytes_sample_message)
153 f.seek(0)
154 key = self._box.add(f)
Petri Lehtinen3d12c432012-08-15 14:00:40 +0300155 self.assertEqual(self._box.get_bytes(key).split(b'\n'),
156 _bytes_sample_message.split(b'\n'))
R. David Murrayb7deff12011-01-30 06:21:28 +0000157
158 def test_add_binary_nonascii_file(self):
159 with tempfile.TemporaryFile('wb+') as f:
160 f.write(self._non_latin_bin_msg)
161 f.seek(0)
162 key = self._box.add(f)
Petri Lehtinen3d12c432012-08-15 14:00:40 +0300163 self.assertEqual(self._box.get_bytes(key).split(b'\n'),
164 self._non_latin_bin_msg.split(b'\n'))
R. David Murrayb7deff12011-01-30 06:21:28 +0000165
166 def test_add_text_file_warns(self):
167 with tempfile.TemporaryFile('w+') as f:
168 f.write(_sample_message)
169 f.seek(0)
170 with self.assertWarns(DeprecationWarning):
171 key = self._box.add(f)
Petri Lehtinen3d12c432012-08-15 14:00:40 +0300172 self.assertEqual(self._box.get_bytes(key).split(b'\n'),
173 _bytes_sample_message.split(b'\n'))
R. David Murrayb7deff12011-01-30 06:21:28 +0000174
175 def test_add_StringIO_warns(self):
176 with self.assertWarns(DeprecationWarning):
177 key = self._box.add(io.StringIO(self._template % "0"))
178 self.assertEqual(self._box.get_string(key), self._template % "0")
179
180 def test_add_nonascii_StringIO_raises(self):
181 with self.assertWarns(DeprecationWarning):
182 with self.assertRaisesRegex(ValueError, "ASCII-only"):
183 self._box.add(io.StringIO(self._nonascii_msg))
R. David Murrayfc141142011-02-11 22:47:17 +0000184 self.assertEqual(len(self._box), 0)
185 self._box.close()
186 self.assertMailboxEmpty()
R. David Murrayb7deff12011-01-30 06:21:28 +0000187
Thomas Wouters477c8d52006-05-27 19:21:47 +0000188 def test_remove(self):
189 # Remove messages using remove()
190 self._test_remove_or_delitem(self._box.remove)
191
192 def test_delitem(self):
193 # Remove messages using __delitem__()
194 self._test_remove_or_delitem(self._box.__delitem__)
195
196 def _test_remove_or_delitem(self, method):
197 # (Used by test_remove() and test_delitem().)
198 key0 = self._box.add(self._template % 0)
199 key1 = self._box.add(self._template % 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000200 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000201 method(key0)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000202 self.assertEqual(len(self._box), 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000203 self.assertRaises(KeyError, lambda: self._box[key0])
204 self.assertRaises(KeyError, lambda: method(key0))
Guido van Rossumea834472007-07-27 05:17:50 +0000205 self.assertEqual(self._box.get_string(key1), self._template % 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000206 key2 = self._box.add(self._template % 2)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000207 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000208 method(key2)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000209 self.assertEqual(len(self._box), 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000210 self.assertRaises(KeyError, lambda: self._box[key2])
211 self.assertRaises(KeyError, lambda: method(key2))
Guido van Rossumea834472007-07-27 05:17:50 +0000212 self.assertEqual(self._box.get_string(key1), self._template % 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000213 method(key1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000214 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000215 self.assertRaises(KeyError, lambda: self._box[key1])
216 self.assertRaises(KeyError, lambda: method(key1))
217
218 def test_discard(self, repetitions=10):
219 # Discard messages
220 key0 = self._box.add(self._template % 0)
221 key1 = self._box.add(self._template % 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000222 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000223 self._box.discard(key0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000224 self.assertEqual(len(self._box), 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000225 self.assertRaises(KeyError, lambda: self._box[key0])
226 self._box.discard(key0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000227 self.assertEqual(len(self._box), 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000228 self.assertRaises(KeyError, lambda: self._box[key0])
229
230 def test_get(self):
231 # Retrieve messages using get()
232 key0 = self._box.add(self._template % 0)
233 msg = self._box.get(key0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000234 self.assertEqual(msg['from'], 'foo')
Petri Lehtinen46809192012-09-25 21:58:51 +0300235 self.assertEqual(msg.get_payload(), '0\n')
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000236 self.assertIs(self._box.get('foo'), None)
237 self.assertIs(self._box.get('foo', False), False)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000238 self._box.close()
Georg Brandlfb16cf12008-05-11 21:31:44 +0000239 self._box = self._factory(self._path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000240 key1 = self._box.add(self._template % 1)
241 msg = self._box.get(key1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000242 self.assertEqual(msg['from'], 'foo')
Petri Lehtinen46809192012-09-25 21:58:51 +0300243 self.assertEqual(msg.get_payload(), '1\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000244
245 def test_getitem(self):
246 # Retrieve message using __getitem__()
247 key0 = self._box.add(self._template % 0)
248 msg = self._box[key0]
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000249 self.assertEqual(msg['from'], 'foo')
Petri Lehtinen46809192012-09-25 21:58:51 +0300250 self.assertEqual(msg.get_payload(), '0\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000251 self.assertRaises(KeyError, lambda: self._box['foo'])
252 self._box.discard(key0)
253 self.assertRaises(KeyError, lambda: self._box[key0])
254
255 def test_get_message(self):
256 # Get Message representations of messages
257 key0 = self._box.add(self._template % 0)
258 key1 = self._box.add(_sample_message)
259 msg0 = self._box.get_message(key0)
Ezio Melottie9615932010-01-24 19:26:24 +0000260 self.assertIsInstance(msg0, mailbox.Message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000261 self.assertEqual(msg0['from'], 'foo')
Petri Lehtinen46809192012-09-25 21:58:51 +0300262 self.assertEqual(msg0.get_payload(), '0\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000263 self._check_sample(self._box.get_message(key1))
264
R. David Murrayb7deff12011-01-30 06:21:28 +0000265 def test_get_bytes(self):
266 # Get bytes representations of messages
267 key0 = self._box.add(self._template % 0)
268 key1 = self._box.add(_sample_message)
269 self.assertEqual(self._box.get_bytes(key0),
270 (self._template % 0).encode('ascii'))
271 self.assertEqual(self._box.get_bytes(key1), _bytes_sample_message)
272
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273 def test_get_string(self):
274 # Get string representations of messages
275 key0 = self._box.add(self._template % 0)
276 key1 = self._box.add(_sample_message)
Guido van Rossumea834472007-07-27 05:17:50 +0000277 self.assertEqual(self._box.get_string(key0), self._template % 0)
R. David Murrayb7deff12011-01-30 06:21:28 +0000278 self.assertEqual(self._box.get_string(key1).split('\n'),
279 _sample_message.split('\n'))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000280
281 def test_get_file(self):
282 # Get file representations of messages
283 key0 = self._box.add(self._template % 0)
284 key1 = self._box.add(_sample_message)
Brett Cannon653238a2010-10-30 00:13:00 +0000285 with self._box.get_file(key0) as file:
286 data0 = file.read()
287 with self._box.get_file(key1) as file:
288 data1 = file.read()
R. David Murrayb7deff12011-01-30 06:21:28 +0000289 self.assertEqual(data0.decode('ascii').replace(os.linesep, '\n'),
Guido van Rossumea834472007-07-27 05:17:50 +0000290 self._template % 0)
R. David Murrayb7deff12011-01-30 06:21:28 +0000291 self.assertEqual(data1.decode('ascii').replace(os.linesep, '\n'),
Guido van Rossumea834472007-07-27 05:17:50 +0000292 _sample_message)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000293
R David Murrayc88bce12011-06-17 22:24:05 -0400294 def test_get_file_can_be_closed_twice(self):
295 # Issue 11700
296 key = self._box.add(_sample_message)
297 f = self._box.get_file(key)
298 f.close()
299 f.close()
300
Thomas Wouters477c8d52006-05-27 19:21:47 +0000301 def test_iterkeys(self):
302 # Get keys using iterkeys()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000303 self._check_iteration(self._box.keys, do_keys=True, do_values=False)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000304
305 def test_keys(self):
306 # Get keys using keys()
307 self._check_iteration(self._box.keys, do_keys=True, do_values=False)
308
309 def test_itervalues(self):
310 # Get values using itervalues()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000311 self._check_iteration(self._box.values, do_keys=False,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000312 do_values=True)
313
314 def test_iter(self):
315 # Get values using __iter__()
316 self._check_iteration(self._box.__iter__, do_keys=False,
317 do_values=True)
318
319 def test_values(self):
320 # Get values using values()
321 self._check_iteration(self._box.values, do_keys=False, do_values=True)
322
323 def test_iteritems(self):
324 # Get keys and values using iteritems()
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000325 self._check_iteration(self._box.items, do_keys=True,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000326 do_values=True)
327
328 def test_items(self):
329 # Get keys and values using items()
330 self._check_iteration(self._box.items, do_keys=True, do_values=True)
331
332 def _check_iteration(self, method, do_keys, do_values, repetitions=10):
333 for value in method():
334 self.fail("Not empty")
335 keys, values = [], []
Guido van Rossum805365e2007-05-07 22:24:25 +0000336 for i in range(repetitions):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000337 keys.append(self._box.add(self._template % i))
338 values.append(self._template % i)
339 if do_keys and not do_values:
340 returned_keys = list(method())
341 elif do_values and not do_keys:
342 returned_values = list(method())
343 else:
344 returned_keys, returned_values = [], []
345 for key, value in method():
346 returned_keys.append(key)
347 returned_values.append(value)
348 if do_keys:
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000349 self.assertEqual(len(keys), len(returned_keys))
350 self.assertEqual(set(keys), set(returned_keys))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000351 if do_values:
352 count = 0
353 for value in returned_values:
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000354 self.assertEqual(value['from'], 'foo')
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000355 self.assertLess(int(value.get_payload()), repetitions)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000356 count += 1
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000357 self.assertEqual(len(values), count)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000358
Thomas Wouters477c8d52006-05-27 19:21:47 +0000359 def test_contains(self):
360 # Check existence of keys using __contains__()
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000361 self.assertNotIn('foo', self._box)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000362 key0 = self._box.add(self._template % 0)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000363 self.assertIn(key0, self._box)
364 self.assertNotIn('foo', self._box)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000365 key1 = self._box.add(self._template % 1)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000366 self.assertIn(key1, self._box)
367 self.assertIn(key0, self._box)
368 self.assertNotIn('foo', self._box)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000369 self._box.remove(key0)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000370 self.assertNotIn(key0, self._box)
371 self.assertIn(key1, self._box)
372 self.assertNotIn('foo', self._box)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000373 self._box.remove(key1)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000374 self.assertNotIn(key1, self._box)
375 self.assertNotIn(key0, self._box)
376 self.assertNotIn('foo', self._box)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000377
378 def test_len(self, repetitions=10):
379 # Get message count
380 keys = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000381 for i in range(repetitions):
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000382 self.assertEqual(len(self._box), i)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000383 keys.append(self._box.add(self._template % i))
Guido van Rossumea834472007-07-27 05:17:50 +0000384 self.assertEqual(len(self._box), i + 1)
Guido van Rossum805365e2007-05-07 22:24:25 +0000385 for i in range(repetitions):
Guido van Rossumea834472007-07-27 05:17:50 +0000386 self.assertEqual(len(self._box), repetitions - i)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000387 self._box.remove(keys[i])
Guido van Rossumea834472007-07-27 05:17:50 +0000388 self.assertEqual(len(self._box), repetitions - i - 1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000389
390 def test_set_item(self):
391 # Modify messages using __setitem__()
392 key0 = self._box.add(self._template % 'original 0')
Guido van Rossumea834472007-07-27 05:17:50 +0000393 self.assertEqual(self._box.get_string(key0),
394 self._template % 'original 0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000395 key1 = self._box.add(self._template % 'original 1')
Guido van Rossumea834472007-07-27 05:17:50 +0000396 self.assertEqual(self._box.get_string(key1),
397 self._template % 'original 1')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000398 self._box[key0] = self._template % 'changed 0'
Guido van Rossumea834472007-07-27 05:17:50 +0000399 self.assertEqual(self._box.get_string(key0),
400 self._template % 'changed 0')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000401 self._box[key1] = self._template % 'changed 1'
Guido van Rossumea834472007-07-27 05:17:50 +0000402 self.assertEqual(self._box.get_string(key1),
403 self._template % 'changed 1')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000404 self._box[key0] = _sample_message
405 self._check_sample(self._box[key0])
406 self._box[key1] = self._box[key0]
407 self._check_sample(self._box[key1])
408 self._box[key0] = self._template % 'original 0'
Guido van Rossumea834472007-07-27 05:17:50 +0000409 self.assertEqual(self._box.get_string(key0),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000410 self._template % 'original 0')
411 self._check_sample(self._box[key1])
412 self.assertRaises(KeyError,
413 lambda: self._box.__setitem__('foo', 'bar'))
414 self.assertRaises(KeyError, lambda: self._box['foo'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000415 self.assertEqual(len(self._box), 2)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000416
417 def test_clear(self, iterations=10):
418 # Remove all messages using clear()
419 keys = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000420 for i in range(iterations):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000421 self._box.add(self._template % i)
422 for i, key in enumerate(keys):
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000423 self.assertEqual(self._box.get_string(key), self._template % i)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000424 self._box.clear()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000425 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000426 for i, key in enumerate(keys):
427 self.assertRaises(KeyError, lambda: self._box.get_string(key))
428
429 def test_pop(self):
430 # Get and remove a message using pop()
431 key0 = self._box.add(self._template % 0)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000432 self.assertIn(key0, self._box)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433 key1 = self._box.add(self._template % 1)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000434 self.assertIn(key1, self._box)
Petri Lehtinen46809192012-09-25 21:58:51 +0300435 self.assertEqual(self._box.pop(key0).get_payload(), '0\n')
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000436 self.assertNotIn(key0, self._box)
437 self.assertIn(key1, self._box)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000438 key2 = self._box.add(self._template % 2)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000439 self.assertIn(key2, self._box)
Petri Lehtinen46809192012-09-25 21:58:51 +0300440 self.assertEqual(self._box.pop(key2).get_payload(), '2\n')
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000441 self.assertNotIn(key2, self._box)
442 self.assertIn(key1, self._box)
Petri Lehtinen46809192012-09-25 21:58:51 +0300443 self.assertEqual(self._box.pop(key1).get_payload(), '1\n')
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000444 self.assertNotIn(key1, self._box)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000445 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446
447 def test_popitem(self, iterations=10):
448 # Get and remove an arbitrary (key, message) using popitem()
449 keys = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000450 for i in range(10):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000451 keys.append(self._box.add(self._template % i))
452 seen = []
Guido van Rossum805365e2007-05-07 22:24:25 +0000453 for i in range(10):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000454 key, msg = self._box.popitem()
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000455 self.assertIn(key, keys)
456 self.assertNotIn(key, seen)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000457 seen.append(key)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000458 self.assertEqual(int(msg.get_payload()), keys.index(key))
459 self.assertEqual(len(self._box), 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000460 for key in keys:
461 self.assertRaises(KeyError, lambda: self._box[key])
462
463 def test_update(self):
464 # Modify multiple messages using update()
465 key0 = self._box.add(self._template % 'original 0')
466 key1 = self._box.add(self._template % 'original 1')
467 key2 = self._box.add(self._template % 'original 2')
468 self._box.update({key0: self._template % 'changed 0',
469 key2: _sample_message})
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000470 self.assertEqual(len(self._box), 3)
Guido van Rossumea834472007-07-27 05:17:50 +0000471 self.assertEqual(self._box.get_string(key0),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000472 self._template % 'changed 0')
Guido van Rossumea834472007-07-27 05:17:50 +0000473 self.assertEqual(self._box.get_string(key1),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000474 self._template % 'original 1')
475 self._check_sample(self._box[key2])
476 self._box.update([(key2, self._template % 'changed 2'),
477 (key1, self._template % 'changed 1'),
478 (key0, self._template % 'original 0')])
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000479 self.assertEqual(len(self._box), 3)
Guido van Rossumea834472007-07-27 05:17:50 +0000480 self.assertEqual(self._box.get_string(key0),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000481 self._template % 'original 0')
Guido van Rossumea834472007-07-27 05:17:50 +0000482 self.assertEqual(self._box.get_string(key1),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000483 self._template % 'changed 1')
Guido van Rossumea834472007-07-27 05:17:50 +0000484 self.assertEqual(self._box.get_string(key2),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000485 self._template % 'changed 2')
486 self.assertRaises(KeyError,
487 lambda: self._box.update({'foo': 'bar',
488 key0: self._template % "changed 0"}))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000489 self.assertEqual(len(self._box), 3)
Guido van Rossumea834472007-07-27 05:17:50 +0000490 self.assertEqual(self._box.get_string(key0),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000491 self._template % "changed 0")
Guido van Rossumea834472007-07-27 05:17:50 +0000492 self.assertEqual(self._box.get_string(key1),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000493 self._template % "changed 1")
Guido van Rossumea834472007-07-27 05:17:50 +0000494 self.assertEqual(self._box.get_string(key2),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000495 self._template % "changed 2")
496
497 def test_flush(self):
498 # Write changes to disk
Christian Heimesf6cd9672008-03-26 13:45:42 +0000499 self._test_flush_or_close(self._box.flush, True)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000500
Petri Lehtinen02653f12012-06-15 20:50:51 +0300501 def test_popitem_and_flush_twice(self):
502 # See #15036.
503 self._box.add(self._template % 0)
504 self._box.add(self._template % 1)
505 self._box.flush()
506
507 self._box.popitem()
508 self._box.flush()
509 self._box.popitem()
510 self._box.flush()
511
Thomas Wouters477c8d52006-05-27 19:21:47 +0000512 def test_lock_unlock(self):
513 # Lock and unlock the mailbox
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000514 self.assertFalse(os.path.exists(self._get_lock_path()))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000515 self._box.lock()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000516 self.assertTrue(os.path.exists(self._get_lock_path()))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000517 self._box.unlock()
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000518 self.assertFalse(os.path.exists(self._get_lock_path()))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000519
520 def test_close(self):
521 # Close mailbox and flush changes to disk
Christian Heimesf6cd9672008-03-26 13:45:42 +0000522 self._test_flush_or_close(self._box.close, False)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000523
Christian Heimesf6cd9672008-03-26 13:45:42 +0000524 def _test_flush_or_close(self, method, should_call_close):
Guido van Rossum805365e2007-05-07 22:24:25 +0000525 contents = [self._template % i for i in range(3)]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000526 self._box.add(contents[0])
527 self._box.add(contents[1])
528 self._box.add(contents[2])
Guido van Rossumc12a8132007-10-26 04:29:23 +0000529 oldbox = self._box
Thomas Wouters477c8d52006-05-27 19:21:47 +0000530 method()
Christian Heimesf6cd9672008-03-26 13:45:42 +0000531 if should_call_close:
532 self._box.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000533 self._box = self._factory(self._path)
534 keys = self._box.keys()
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000535 self.assertEqual(len(keys), 3)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536 for key in keys:
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000537 self.assertIn(self._box.get_string(key), contents)
Guido van Rossumc12a8132007-10-26 04:29:23 +0000538 oldbox.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000539
540 def test_dump_message(self):
541 # Write message representations to disk
542 for input in (email.message_from_string(_sample_message),
R. David Murrayb7deff12011-01-30 06:21:28 +0000543 _sample_message, io.BytesIO(_bytes_sample_message)):
544 output = io.BytesIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545 self._box._dump_message(input, output)
R. David Murrayb7deff12011-01-30 06:21:28 +0000546 self.assertEqual(output.getvalue(),
547 _bytes_sample_message.replace(b'\n', os.linesep.encode()))
548 output = io.BytesIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000549 self.assertRaises(TypeError,
550 lambda: self._box._dump_message(None, output))
551
552 def _get_lock_path(self):
553 # Return the path of the dot lock file. May be overridden.
554 return self._path + '.lock'
555
556
R David Murray317c8d22012-04-08 16:46:18 -0400557class TestMailboxSuperclass(TestBase, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000558
559 def test_notimplemented(self):
560 # Test that all Mailbox methods raise NotImplementedException.
561 box = mailbox.Mailbox('path')
562 self.assertRaises(NotImplementedError, lambda: box.add(''))
563 self.assertRaises(NotImplementedError, lambda: box.remove(''))
564 self.assertRaises(NotImplementedError, lambda: box.__delitem__(''))
565 self.assertRaises(NotImplementedError, lambda: box.discard(''))
566 self.assertRaises(NotImplementedError, lambda: box.__setitem__('', ''))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000567 self.assertRaises(NotImplementedError, lambda: box.keys())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000568 self.assertRaises(NotImplementedError, lambda: box.keys())
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000569 self.assertRaises(NotImplementedError, lambda: box.values().__next__())
570 self.assertRaises(NotImplementedError, lambda: box.__iter__().__next__())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000571 self.assertRaises(NotImplementedError, lambda: box.values())
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000572 self.assertRaises(NotImplementedError, lambda: box.items().next())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000573 self.assertRaises(NotImplementedError, lambda: box.items())
574 self.assertRaises(NotImplementedError, lambda: box.get(''))
575 self.assertRaises(NotImplementedError, lambda: box.__getitem__(''))
576 self.assertRaises(NotImplementedError, lambda: box.get_message(''))
577 self.assertRaises(NotImplementedError, lambda: box.get_string(''))
R. David Murrayb7deff12011-01-30 06:21:28 +0000578 self.assertRaises(NotImplementedError, lambda: box.get_bytes(''))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000579 self.assertRaises(NotImplementedError, lambda: box.get_file(''))
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000580 self.assertRaises(NotImplementedError, lambda: '' in box)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000581 self.assertRaises(NotImplementedError, lambda: box.__contains__(''))
582 self.assertRaises(NotImplementedError, lambda: box.__len__())
583 self.assertRaises(NotImplementedError, lambda: box.clear())
584 self.assertRaises(NotImplementedError, lambda: box.pop(''))
585 self.assertRaises(NotImplementedError, lambda: box.popitem())
586 self.assertRaises(NotImplementedError, lambda: box.update((('', ''),)))
587 self.assertRaises(NotImplementedError, lambda: box.flush())
588 self.assertRaises(NotImplementedError, lambda: box.lock())
589 self.assertRaises(NotImplementedError, lambda: box.unlock())
590 self.assertRaises(NotImplementedError, lambda: box.close())
591
592
R David Murray317c8d22012-04-08 16:46:18 -0400593class TestMaildir(TestMailbox, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000594
595 _factory = lambda self, path, factory=None: mailbox.Maildir(path, factory)
596
597 def setUp(self):
598 TestMailbox.setUp(self)
Jesus Ceaf01d6952012-10-05 03:36:11 +0200599 if (os.name == 'nt') or (sys.platform == 'cygwin'):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000600 self._box.colon = '!'
601
R. David Murrayfc141142011-02-11 22:47:17 +0000602 def assertMailboxEmpty(self):
603 self.assertEqual(os.listdir(os.path.join(self._path, 'tmp')), [])
604
Thomas Wouters477c8d52006-05-27 19:21:47 +0000605 def test_add_MM(self):
606 # Add a MaildirMessage instance
607 msg = mailbox.MaildirMessage(self._template % 0)
608 msg.set_subdir('cur')
609 msg.set_info('foo')
610 key = self._box.add(msg)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000611 self.assertTrue(os.path.exists(os.path.join(self._path, 'cur', '%s%sfoo' %
Thomas Wouters477c8d52006-05-27 19:21:47 +0000612 (key, self._box.colon))))
613
614 def test_get_MM(self):
615 # Get a MaildirMessage instance
616 msg = mailbox.MaildirMessage(self._template % 0)
617 msg.set_subdir('cur')
618 msg.set_flags('RF')
619 key = self._box.add(msg)
620 msg_returned = self._box.get_message(key)
Ezio Melottie9615932010-01-24 19:26:24 +0000621 self.assertIsInstance(msg_returned, mailbox.MaildirMessage)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000622 self.assertEqual(msg_returned.get_subdir(), 'cur')
623 self.assertEqual(msg_returned.get_flags(), 'FR')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000624
625 def test_set_MM(self):
626 # Set with a MaildirMessage instance
627 msg0 = mailbox.MaildirMessage(self._template % 0)
628 msg0.set_flags('TP')
629 key = self._box.add(msg0)
630 msg_returned = self._box.get_message(key)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000631 self.assertEqual(msg_returned.get_subdir(), 'new')
632 self.assertEqual(msg_returned.get_flags(), 'PT')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000633 msg1 = mailbox.MaildirMessage(self._template % 1)
634 self._box[key] = msg1
635 msg_returned = self._box.get_message(key)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000636 self.assertEqual(msg_returned.get_subdir(), 'new')
637 self.assertEqual(msg_returned.get_flags(), '')
Petri Lehtinen46809192012-09-25 21:58:51 +0300638 self.assertEqual(msg_returned.get_payload(), '1\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000639 msg2 = mailbox.MaildirMessage(self._template % 2)
640 msg2.set_info('2,S')
641 self._box[key] = msg2
642 self._box[key] = self._template % 3
643 msg_returned = self._box.get_message(key)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000644 self.assertEqual(msg_returned.get_subdir(), 'new')
645 self.assertEqual(msg_returned.get_flags(), 'S')
Petri Lehtinen46809192012-09-25 21:58:51 +0300646 self.assertEqual(msg_returned.get_payload(), '3\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000647
Christian Heimesfdab48e2008-01-20 09:06:41 +0000648 def test_consistent_factory(self):
649 # Add a message.
650 msg = mailbox.MaildirMessage(self._template % 0)
651 msg.set_subdir('cur')
652 msg.set_flags('RF')
653 key = self._box.add(msg)
654
655 # Create new mailbox with
656 class FakeMessage(mailbox.MaildirMessage):
657 pass
658 box = mailbox.Maildir(self._path, factory=FakeMessage)
Christian Heimes15ebc882008-02-04 18:48:49 +0000659 box.colon = self._box.colon
Christian Heimesfdab48e2008-01-20 09:06:41 +0000660 msg2 = box.get_message(key)
Ezio Melottie9615932010-01-24 19:26:24 +0000661 self.assertIsInstance(msg2, FakeMessage)
Christian Heimesfdab48e2008-01-20 09:06:41 +0000662
Thomas Wouters477c8d52006-05-27 19:21:47 +0000663 def test_initialize_new(self):
664 # Initialize a non-existent mailbox
665 self.tearDown()
666 self._box = mailbox.Maildir(self._path)
Georg Brandlfb16cf12008-05-11 21:31:44 +0000667 self._check_basics()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000668 self._delete_recursively(self._path)
669 self._box = self._factory(self._path, factory=None)
670 self._check_basics()
671
672 def test_initialize_existing(self):
673 # Initialize an existing mailbox
674 self.tearDown()
675 for subdir in '', 'tmp', 'new', 'cur':
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000676 os.mkdir(os.path.normpath(os.path.join(self._path, subdir)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000677 self._box = mailbox.Maildir(self._path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000678 self._check_basics()
679
680 def _check_basics(self, factory=None):
681 # (Used by test_open_new() and test_open_existing().)
682 self.assertEqual(self._box._path, os.path.abspath(self._path))
683 self.assertEqual(self._box._factory, factory)
684 for subdir in '', 'tmp', 'new', 'cur':
685 path = os.path.join(self._path, subdir)
686 mode = os.stat(path)[stat.ST_MODE]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000687 self.assertTrue(stat.S_ISDIR(mode), "Not a directory: '%s'" % path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000688
689 def test_list_folders(self):
690 # List folders
691 self._box.add_folder('one')
692 self._box.add_folder('two')
693 self._box.add_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000694 self.assertEqual(len(self._box.list_folders()), 3)
Guido van Rossumea834472007-07-27 05:17:50 +0000695 self.assertEqual(set(self._box.list_folders()),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000696 set(('one', 'two', 'three')))
697
698 def test_get_folder(self):
699 # Open folders
700 self._box.add_folder('foo.bar')
701 folder0 = self._box.get_folder('foo.bar')
702 folder0.add(self._template % 'bar')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000703 self.assertTrue(os.path.isdir(os.path.join(self._path, '.foo.bar')))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000704 folder1 = self._box.get_folder('foo.bar')
Guido van Rossumea834472007-07-27 05:17:50 +0000705 self.assertEqual(folder1.get_string(folder1.keys()[0]),
706 self._template % 'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000707
708 def test_add_and_remove_folders(self):
709 # Delete folders
710 self._box.add_folder('one')
711 self._box.add_folder('two')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000712 self.assertEqual(len(self._box.list_folders()), 2)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000713 self.assertEqual(set(self._box.list_folders()), set(('one', 'two')))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000714 self._box.remove_folder('one')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000715 self.assertEqual(len(self._box.list_folders()), 1)
716 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717 self._box.add_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000718 self.assertEqual(len(self._box.list_folders()), 2)
Guido van Rossumea834472007-07-27 05:17:50 +0000719 self.assertEqual(set(self._box.list_folders()), set(('two', 'three')))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000720 self._box.remove_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000721 self.assertEqual(len(self._box.list_folders()), 1)
722 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000723 self._box.remove_folder('two')
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000724 self.assertEqual(len(self._box.list_folders()), 0)
725 self.assertEqual(self._box.list_folders(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +0000726
727 def test_clean(self):
728 # Remove old files from 'tmp'
729 foo_path = os.path.join(self._path, 'tmp', 'foo')
730 bar_path = os.path.join(self._path, 'tmp', 'bar')
Brian Curtin5acec042010-10-13 02:29:46 +0000731 with open(foo_path, 'w') as f:
732 f.write("@")
733 with open(bar_path, 'w') as f:
734 f.write("@")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000735 self._box.clean()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000736 self.assertTrue(os.path.exists(foo_path))
737 self.assertTrue(os.path.exists(bar_path))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000738 foo_stat = os.stat(foo_path)
739 os.utime(foo_path, (time.time() - 129600 - 2,
740 foo_stat.st_mtime))
741 self._box.clean()
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000742 self.assertFalse(os.path.exists(foo_path))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000743 self.assertTrue(os.path.exists(bar_path))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000744
745 def test_create_tmp(self, repetitions=10):
746 # Create files in tmp directory
747 hostname = socket.gethostname()
748 if '/' in hostname:
749 hostname = hostname.replace('/', r'\057')
750 if ':' in hostname:
751 hostname = hostname.replace(':', r'\072')
752 pid = os.getpid()
753 pattern = re.compile(r"(?P<time>\d+)\.M(?P<M>\d{1,6})P(?P<P>\d+)"
754 r"Q(?P<Q>\d+)\.(?P<host>[^:/]+)")
755 previous_groups = None
Guido van Rossum805365e2007-05-07 22:24:25 +0000756 for x in range(repetitions):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000757 tmp_file = self._box._create_tmp()
758 head, tail = os.path.split(tmp_file.name)
759 self.assertEqual(head, os.path.abspath(os.path.join(self._path,
760 "tmp")),
761 "File in wrong location: '%s'" % head)
762 match = pattern.match(tail)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000763 self.assertIsNot(match, None, "Invalid file name: '%s'" % tail)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000764 groups = match.groups()
Benjamin Peterson2a691a82008-03-31 01:51:45 +0000765 if previous_groups is not None:
Petri Lehtinen1c371b22012-09-01 14:22:36 +0300766 self.assertGreaterEqual(int(groups[0]), int(previous_groups[0]),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000767 "Non-monotonic seconds: '%s' before '%s'" %
768 (previous_groups[0], groups[0]))
Petri Lehtinen1c371b22012-09-01 14:22:36 +0300769 if int(groups[0]) == int(previous_groups[0]):
770 self.assertGreaterEqual(int(groups[1]), int(previous_groups[1]),
771 "Non-monotonic milliseconds: '%s' before '%s'" %
772 (previous_groups[1], groups[1]))
Guido van Rossumea834472007-07-27 05:17:50 +0000773 self.assertEqual(int(groups[2]), pid,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000774 "Process ID mismatch: '%s' should be '%s'" %
775 (groups[2], pid))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000776 self.assertEqual(int(groups[3]), int(previous_groups[3]) + 1,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000777 "Non-sequential counter: '%s' before '%s'" %
778 (previous_groups[3], groups[3]))
Guido van Rossumea834472007-07-27 05:17:50 +0000779 self.assertEqual(groups[4], hostname,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000780 "Host name mismatch: '%s' should be '%s'" %
781 (groups[4], hostname))
782 previous_groups = groups
R. David Murrayb7deff12011-01-30 06:21:28 +0000783 tmp_file.write(_bytes_sample_message)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000784 tmp_file.seek(0)
R. David Murrayb7deff12011-01-30 06:21:28 +0000785 self.assertEqual(tmp_file.read(), _bytes_sample_message)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000786 tmp_file.close()
787 file_count = len(os.listdir(os.path.join(self._path, "tmp")))
Guido van Rossumea834472007-07-27 05:17:50 +0000788 self.assertEqual(file_count, repetitions,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000789 "Wrong file count: '%s' should be '%s'" %
790 (file_count, repetitions))
791
792 def test_refresh(self):
793 # Update the table of contents
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000794 self.assertEqual(self._box._toc, {})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000795 key0 = self._box.add(self._template % 0)
796 key1 = self._box.add(self._template % 1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000797 self.assertEqual(self._box._toc, {})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000798 self._box._refresh()
Guido van Rossumea834472007-07-27 05:17:50 +0000799 self.assertEqual(self._box._toc, {key0: os.path.join('new', key0),
800 key1: os.path.join('new', key1)})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000801 key2 = self._box.add(self._template % 2)
Guido van Rossumea834472007-07-27 05:17:50 +0000802 self.assertEqual(self._box._toc, {key0: os.path.join('new', key0),
803 key1: os.path.join('new', key1)})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000804 self._box._refresh()
Guido van Rossumea834472007-07-27 05:17:50 +0000805 self.assertEqual(self._box._toc, {key0: os.path.join('new', key0),
806 key1: os.path.join('new', key1),
807 key2: os.path.join('new', key2)})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000808
Petri Lehtinen8c482ee2011-11-05 09:44:59 +0200809 def test_refresh_after_safety_period(self):
810 # Issue #13254: Call _refresh after the "file system safety
811 # period" of 2 seconds has passed; _toc should still be
812 # updated because this is the first call to _refresh.
813 key0 = self._box.add(self._template % 0)
814 key1 = self._box.add(self._template % 1)
815
816 self._box = self._factory(self._path)
817 self.assertEqual(self._box._toc, {})
818
819 # Emulate sleeping. Instead of sleeping for 2 seconds, use the
820 # skew factor to make _refresh think that the filesystem
821 # safety period has passed and re-reading the _toc is only
822 # required if mtimes differ.
Petri Lehtinenc153cd32011-11-12 21:02:42 +0200823 self._box._skewfactor = -3
Petri Lehtinen8c482ee2011-11-05 09:44:59 +0200824
825 self._box._refresh()
826 self.assertEqual(sorted(self._box._toc.keys()), sorted([key0, key1]))
827
Thomas Wouters477c8d52006-05-27 19:21:47 +0000828 def test_lookup(self):
829 # Look up message subpaths in the TOC
830 self.assertRaises(KeyError, lambda: self._box._lookup('foo'))
831 key0 = self._box.add(self._template % 0)
Guido van Rossumea834472007-07-27 05:17:50 +0000832 self.assertEqual(self._box._lookup(key0), os.path.join('new', key0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000833 os.remove(os.path.join(self._path, 'new', key0))
Guido van Rossumea834472007-07-27 05:17:50 +0000834 self.assertEqual(self._box._toc, {key0: os.path.join('new', key0)})
Antoine Pitrou03f13442009-11-02 11:36:51 +0000835 # Be sure that the TOC is read back from disk (see issue #6896
836 # about bad mtime behaviour on some systems).
837 self._box.flush()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000838 self.assertRaises(KeyError, lambda: self._box._lookup(key0))
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000839 self.assertEqual(self._box._toc, {})
Thomas Wouters477c8d52006-05-27 19:21:47 +0000840
841 def test_lock_unlock(self):
842 # Lock and unlock the mailbox. For Maildir, this does nothing.
843 self._box.lock()
844 self._box.unlock()
845
Thomas Wouters89f507f2006-12-13 04:49:30 +0000846 def test_folder (self):
847 # Test for bug #1569790: verify that folders returned by .get_folder()
848 # use the same factory function.
849 def dummy_factory (s):
850 return None
851 box = self._factory(self._path, factory=dummy_factory)
852 folder = box.add_folder('folder1')
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000853 self.assertIs(folder._factory, dummy_factory)
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000854
Thomas Wouters89f507f2006-12-13 04:49:30 +0000855 folder1_alias = box.get_folder('folder1')
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000856 self.assertIs(folder1_alias._factory, dummy_factory)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000857
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000858 def test_directory_in_folder (self):
859 # Test that mailboxes still work if there's a stray extra directory
860 # in a folder.
861 for i in range(10):
862 self._box.add(mailbox.Message(_sample_message))
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000863
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000864 # Create a stray directory
865 os.mkdir(os.path.join(self._path, 'cur', 'stray-dir'))
866
867 # Check that looping still works with the directory present.
868 for msg in self._box:
869 pass
Thomas Wouters477c8d52006-05-27 19:21:47 +0000870
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000871 def test_file_permissions(self):
872 # Verify that message files are created without execute permissions
873 if not hasattr(os, "stat") or not hasattr(os, "umask"):
874 return
875 msg = mailbox.MaildirMessage(self._template % 0)
876 orig_umask = os.umask(0)
877 try:
878 key = self._box.add(msg)
879 finally:
880 os.umask(orig_umask)
881 path = os.path.join(self._path, self._box._lookup(key))
882 mode = os.stat(path).st_mode
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +0000883 self.assertFalse(mode & 0o111)
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000884
885 def test_folder_file_perms(self):
886 # From bug #3228, we want to verify that the file created inside a Maildir
887 # subfolder isn't marked as executable.
888 if not hasattr(os, "stat") or not hasattr(os, "umask"):
889 return
890
891 orig_umask = os.umask(0)
892 try:
893 subfolder = self._box.add_folder('subfolder')
894 finally:
895 os.umask(orig_umask)
896
897 path = os.path.join(subfolder._path, 'maildirfolder')
898 st = os.stat(path)
899 perms = st.st_mode
900 self.assertFalse((perms & 0o111)) # Execute bits should all be off.
901
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000902 def test_reread(self):
Petri Lehtinen8c482ee2011-11-05 09:44:59 +0200903 # Do an initial unconditional refresh
904 self._box._refresh()
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000905
R David Murraycaed7fe2011-05-06 22:07:19 -0400906 # Put the last modified times more than two seconds into the past
907 # (because mtime may have a two second granularity)
R David Murrayb9a428d2011-03-25 16:03:47 -0400908 for subdir in ('cur', 'new'):
909 os.utime(os.path.join(self._box._path, subdir),
910 (time.time()-5,)*2)
911
R David Murraycaed7fe2011-05-06 22:07:19 -0400912 # Because mtime has a two second granularity in worst case (FAT), a
913 # refresh is done unconditionally if called for within
914 # two-second-plus-a-bit of the last one, just in case the mbox has
915 # changed; so now we have to wait for that interval to expire.
Petri Lehtinenc153cd32011-11-12 21:02:42 +0200916 #
917 # Because this is a test, emulate sleeping. Instead of
918 # sleeping for 2 seconds, use the skew factor to make _refresh
919 # think that 2 seconds have passed and re-reading the _toc is
920 # only required if mtimes differ.
921 self._box._skewfactor = -3
R David Murraycaed7fe2011-05-06 22:07:19 -0400922
R David Murrayb9a428d2011-03-25 16:03:47 -0400923 # Re-reading causes the ._toc attribute to be assigned a new dictionary
924 # object, so we'll check that the ._toc attribute isn't a different
925 # object.
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000926 orig_toc = self._box._toc
927 def refreshed():
928 return self._box._toc is not orig_toc
929
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000930 self._box._refresh()
R David Murraycaed7fe2011-05-06 22:07:19 -0400931 self.assertFalse(refreshed())
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000932
933 # Now, write something into cur and remove it. This changes
Petri Lehtinenc153cd32011-11-12 21:02:42 +0200934 # the mtime and should cause a re-read. Note that "sleep
935 # emulation" is still in effect, as skewfactor is -3.
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000936 filename = os.path.join(self._path, 'cur', 'stray-file')
Victor Stinnerbf816222011-06-30 23:25:47 +0200937 support.create_empty_file(filename)
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000938 os.unlink(filename)
939 self._box._refresh()
R David Murraycaed7fe2011-05-06 22:07:19 -0400940 self.assertTrue(refreshed())
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000941
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300942
943class _TestSingleFile(TestMailbox):
944 '''Common tests for single-file mailboxes'''
945
946 def test_add_doesnt_rewrite(self):
947 # When only adding messages, flush() should not rewrite the
948 # mailbox file. See issue #9559.
949
950 # Inode number changes if the contents are written to another
951 # file which is then renamed over the original file. So we
952 # must check that the inode number doesn't change.
953 inode_before = os.stat(self._path).st_ino
954
955 self._box.add(self._template % 0)
956 self._box.flush()
957
958 inode_after = os.stat(self._path).st_ino
959 self.assertEqual(inode_before, inode_after)
960
961 # Make sure the message was really added
962 self._box.close()
963 self._box = self._factory(self._path)
964 self.assertEqual(len(self._box), 1)
965
Petri Lehtinen5b5619f2012-06-29 15:09:12 +0300966 def test_permissions_after_flush(self):
967 # See issue #5346
968
969 # Make the mailbox world writable. It's unlikely that the new
970 # mailbox file would have these permissions after flush(),
971 # because umask usually prevents it.
972 mode = os.stat(self._path).st_mode | 0o666
973 os.chmod(self._path, mode)
974
975 self._box.add(self._template % 0)
976 i = self._box.add(self._template % 1)
977 # Need to remove one message to make flush() create a new file
978 self._box.remove(i)
979 self._box.flush()
980
981 self.assertEqual(os.stat(self._path).st_mode, mode)
982
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300983
984class _TestMboxMMDF(_TestSingleFile):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000985
986 def tearDown(self):
Brett Cannon653238a2010-10-30 00:13:00 +0000987 super().tearDown()
Guido van Rossumc12a8132007-10-26 04:29:23 +0000988 self._box.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000989 self._delete_recursively(self._path)
990 for lock_remnant in glob.glob(self._path + '.*'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000991 support.unlink(lock_remnant)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000992
R. David Murrayfc141142011-02-11 22:47:17 +0000993 def assertMailboxEmpty(self):
994 with open(self._path) as f:
995 self.assertEqual(f.readlines(), [])
996
Thomas Wouters477c8d52006-05-27 19:21:47 +0000997 def test_add_from_string(self):
998 # Add a string starting with 'From ' to the mailbox
Petri Lehtinen46809192012-09-25 21:58:51 +0300999 key = self._box.add('From foo@bar blah\nFrom: foo\n\n0\n')
Guido van Rossumea834472007-07-27 05:17:50 +00001000 self.assertEqual(self._box[key].get_from(), 'foo@bar blah')
Petri Lehtinen46809192012-09-25 21:58:51 +03001001 self.assertEqual(self._box[key].get_payload(), '0\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001002
R. David Murrayb7deff12011-01-30 06:21:28 +00001003 def test_add_from_bytes(self):
1004 # Add a byte string starting with 'From ' to the mailbox
Petri Lehtinen46809192012-09-25 21:58:51 +03001005 key = self._box.add(b'From foo@bar blah\nFrom: foo\n\n0\n')
R. David Murrayb7deff12011-01-30 06:21:28 +00001006 self.assertEqual(self._box[key].get_from(), 'foo@bar blah')
Petri Lehtinen46809192012-09-25 21:58:51 +03001007 self.assertEqual(self._box[key].get_payload(), '0\n')
R. David Murrayb7deff12011-01-30 06:21:28 +00001008
Thomas Wouters477c8d52006-05-27 19:21:47 +00001009 def test_add_mbox_or_mmdf_message(self):
1010 # Add an mboxMessage or MMDFMessage
1011 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
Petri Lehtinen46809192012-09-25 21:58:51 +03001012 msg = class_('From foo@bar blah\nFrom: foo\n\n0\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001013 key = self._box.add(msg)
1014
1015 def test_open_close_open(self):
1016 # Open and inspect previously-created mailbox
Guido van Rossum805365e2007-05-07 22:24:25 +00001017 values = [self._template % i for i in range(3)]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001018 for value in values:
1019 self._box.add(value)
1020 self._box.close()
1021 mtime = os.path.getmtime(self._path)
1022 self._box = self._factory(self._path)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001023 self.assertEqual(len(self._box), 3)
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001024 for key in self._box.keys():
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00001025 self.assertIn(self._box.get_string(key), values)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001026 self._box.close()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001027 self.assertEqual(mtime, os.path.getmtime(self._path))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001028
1029 def test_add_and_close(self):
1030 # Verifying that closing a mailbox doesn't change added items
1031 self._box.add(_sample_message)
Guido van Rossum805365e2007-05-07 22:24:25 +00001032 for i in range(3):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001033 self._box.add(self._template % i)
1034 self._box.add(_sample_message)
1035 self._box._file.flush()
1036 self._box._file.seek(0)
1037 contents = self._box._file.read()
1038 self._box.close()
R. David Murrayb7deff12011-01-30 06:21:28 +00001039 with open(self._path, 'rb') as f:
Brian Curtin5acec042010-10-13 02:29:46 +00001040 self.assertEqual(contents, f.read())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001041 self._box = self._factory(self._path)
1042
Charles-François Natali78ed83d2011-12-19 12:18:55 +01001043 @unittest.skipUnless(hasattr(os, 'fork'), "Test needs fork().")
Charles-François Natalibf383152011-12-20 11:48:22 +01001044 @unittest.skipUnless(hasattr(socket, 'socketpair'), "Test needs socketpair().")
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001045 def test_lock_conflict(self):
Charles-François Natali78ed83d2011-12-19 12:18:55 +01001046 # Fork off a child process that will lock the mailbox temporarily,
1047 # unlock it and exit.
Charles-François Natalibf383152011-12-20 11:48:22 +01001048 c, p = socket.socketpair()
1049 self.addCleanup(c.close)
1050 self.addCleanup(p.close)
Charles-François Natali78ed83d2011-12-19 12:18:55 +01001051
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001052 pid = os.fork()
1053 if pid == 0:
Charles-François Natali78ed83d2011-12-19 12:18:55 +01001054 # child
Guido van Rossum62cbc8a2007-04-09 00:41:25 +00001055 try:
Charles-François Natali78ed83d2011-12-19 12:18:55 +01001056 # lock the mailbox, and signal the parent it can proceed
Guido van Rossum62cbc8a2007-04-09 00:41:25 +00001057 self._box.lock()
Charles-François Natalibf383152011-12-20 11:48:22 +01001058 c.send(b'c')
Charles-François Natali78ed83d2011-12-19 12:18:55 +01001059
1060 # wait until the parent is done, and unlock the mailbox
Charles-François Natalibf383152011-12-20 11:48:22 +01001061 c.recv(1)
Guido van Rossum62cbc8a2007-04-09 00:41:25 +00001062 self._box.unlock()
1063 finally:
1064 os._exit(0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001065
Charles-François Natali78ed83d2011-12-19 12:18:55 +01001066 # In the parent, wait until the child signals it locked the mailbox.
Charles-François Natalibf383152011-12-20 11:48:22 +01001067 p.recv(1)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001068 try:
1069 self.assertRaises(mailbox.ExternalClashError,
1070 self._box.lock)
1071 finally:
Charles-François Natali78ed83d2011-12-19 12:18:55 +01001072 # Signal the child it can now release the lock and exit.
Charles-François Natalibf383152011-12-20 11:48:22 +01001073 p.send(b'p')
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001074 # Wait for child to exit. Locking should now succeed.
1075 exited_pid, status = os.waitpid(pid, 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001076
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001077 self._box.lock()
1078 self._box.unlock()
1079
Thomas Wouters89f507f2006-12-13 04:49:30 +00001080 def test_relock(self):
1081 # Test case for bug #1575506: the mailbox class was locking the
1082 # wrong file object in its flush() method.
1083 msg = "Subject: sub\n\nbody\n"
1084 key1 = self._box.add(msg)
1085 self._box.flush()
1086 self._box.close()
1087
1088 self._box = self._factory(self._path)
1089 self._box.lock()
1090 key2 = self._box.add(msg)
1091 self._box.flush()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001092 self.assertTrue(self._box._locked)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001093 self._box.close()
1094
1095
R David Murray317c8d22012-04-08 16:46:18 -04001096class TestMbox(_TestMboxMMDF, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001097
1098 _factory = lambda self, path, factory=None: mailbox.mbox(path, factory)
1099
Georg Brandl6aa2d1f2008-08-12 08:35:52 +00001100 def test_file_perms(self):
1101 # From bug #3228, we want to verify that the mailbox file isn't executable,
1102 # even if the umask is set to something that would leave executable bits set.
1103 # We only run this test on platforms that support umask.
1104 if hasattr(os, 'umask') and hasattr(os, 'stat'):
1105 try:
1106 old_umask = os.umask(0o077)
1107 self._box.close()
1108 os.unlink(self._path)
1109 self._box = mailbox.mbox(self._path, create=True)
1110 self._box.add('')
1111 self._box.close()
1112 finally:
1113 os.umask(old_umask)
1114
1115 st = os.stat(self._path)
1116 perms = st.st_mode
1117 self.assertFalse((perms & 0o111)) # Execute bits should all be off.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001118
Petri Lehtinenf39884b2012-09-25 22:00:32 +03001119 def test_terminating_newline(self):
1120 message = email.message.Message()
1121 message['From'] = 'john@example.com'
1122 message.set_payload('No newline at the end')
1123 i = self._box.add(message)
1124
1125 # A newline should have been appended to the payload
1126 message = self._box.get(i)
1127 self.assertEqual(message.get_payload(), 'No newline at the end\n')
1128
1129 def test_message_separator(self):
1130 # Check there's always a single blank line after each message
1131 self._box.add('From: foo\n\n0') # No newline at the end
1132 with open(self._path) as f:
1133 data = f.read()
1134 self.assertEqual(data[-3:], '0\n\n')
1135
1136 self._box.add('From: foo\n\n0\n') # Newline at the end
1137 with open(self._path) as f:
1138 data = f.read()
1139 self.assertEqual(data[-3:], '0\n\n')
1140
1141
R David Murray317c8d22012-04-08 16:46:18 -04001142class TestMMDF(_TestMboxMMDF, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001143
1144 _factory = lambda self, path, factory=None: mailbox.MMDF(path, factory)
1145
1146
R David Murray317c8d22012-04-08 16:46:18 -04001147class TestMH(TestMailbox, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001148
1149 _factory = lambda self, path, factory=None: mailbox.MH(path, factory)
1150
R. David Murrayfc141142011-02-11 22:47:17 +00001151 def assertMailboxEmpty(self):
1152 self.assertEqual(os.listdir(self._path), ['.mh_sequences'])
1153
Thomas Wouters477c8d52006-05-27 19:21:47 +00001154 def test_list_folders(self):
1155 # List folders
1156 self._box.add_folder('one')
1157 self._box.add_folder('two')
1158 self._box.add_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001159 self.assertEqual(len(self._box.list_folders()), 3)
Guido van Rossumea834472007-07-27 05:17:50 +00001160 self.assertEqual(set(self._box.list_folders()),
Thomas Wouters477c8d52006-05-27 19:21:47 +00001161 set(('one', 'two', 'three')))
1162
1163 def test_get_folder(self):
1164 # Open folders
Thomas Wouters89f507f2006-12-13 04:49:30 +00001165 def dummy_factory (s):
1166 return None
1167 self._box = self._factory(self._path, dummy_factory)
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001168
Thomas Wouters89f507f2006-12-13 04:49:30 +00001169 new_folder = self._box.add_folder('foo.bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001170 folder0 = self._box.get_folder('foo.bar')
1171 folder0.add(self._template % 'bar')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001172 self.assertTrue(os.path.isdir(os.path.join(self._path, 'foo.bar')))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001173 folder1 = self._box.get_folder('foo.bar')
Guido van Rossumea834472007-07-27 05:17:50 +00001174 self.assertEqual(folder1.get_string(folder1.keys()[0]),
1175 self._template % 'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001176
Thomas Wouters89f507f2006-12-13 04:49:30 +00001177 # Test for bug #1569790: verify that folders returned by .get_folder()
1178 # use the same factory function.
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00001179 self.assertIs(new_folder._factory, self._box._factory)
1180 self.assertIs(folder0._factory, self._box._factory)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001181
Thomas Wouters477c8d52006-05-27 19:21:47 +00001182 def test_add_and_remove_folders(self):
1183 # Delete folders
1184 self._box.add_folder('one')
1185 self._box.add_folder('two')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001186 self.assertEqual(len(self._box.list_folders()), 2)
Guido van Rossumea834472007-07-27 05:17:50 +00001187 self.assertEqual(set(self._box.list_folders()), set(('one', 'two')))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001188 self._box.remove_folder('one')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001189 self.assertEqual(len(self._box.list_folders()), 1)
1190 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001191 self._box.add_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001192 self.assertEqual(len(self._box.list_folders()), 2)
Guido van Rossumea834472007-07-27 05:17:50 +00001193 self.assertEqual(set(self._box.list_folders()), set(('two', 'three')))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001194 self._box.remove_folder('three')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001195 self.assertEqual(len(self._box.list_folders()), 1)
1196 self.assertEqual(set(self._box.list_folders()), set(('two',)))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001197 self._box.remove_folder('two')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001198 self.assertEqual(len(self._box.list_folders()), 0)
1199 self.assertEqual(self._box.list_folders(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001200
1201 def test_sequences(self):
1202 # Get and set sequences
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001203 self.assertEqual(self._box.get_sequences(), {})
Thomas Wouters477c8d52006-05-27 19:21:47 +00001204 msg0 = mailbox.MHMessage(self._template % 0)
1205 msg0.add_sequence('foo')
1206 key0 = self._box.add(msg0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001207 self.assertEqual(self._box.get_sequences(), {'foo':[key0]})
Thomas Wouters477c8d52006-05-27 19:21:47 +00001208 msg1 = mailbox.MHMessage(self._template % 1)
1209 msg1.set_sequences(['bar', 'replied', 'foo'])
1210 key1 = self._box.add(msg1)
Guido van Rossumea834472007-07-27 05:17:50 +00001211 self.assertEqual(self._box.get_sequences(),
Thomas Wouters477c8d52006-05-27 19:21:47 +00001212 {'foo':[key0, key1], 'bar':[key1], 'replied':[key1]})
1213 msg0.set_sequences(['flagged'])
1214 self._box[key0] = msg0
Guido van Rossumea834472007-07-27 05:17:50 +00001215 self.assertEqual(self._box.get_sequences(),
Thomas Wouters477c8d52006-05-27 19:21:47 +00001216 {'foo':[key1], 'bar':[key1], 'replied':[key1],
1217 'flagged':[key0]})
1218 self._box.remove(key1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001219 self.assertEqual(self._box.get_sequences(), {'flagged':[key0]})
Thomas Wouters477c8d52006-05-27 19:21:47 +00001220
R. David Murray548ac412009-04-02 19:44:43 +00001221 def test_issue2625(self):
1222 msg0 = mailbox.MHMessage(self._template % 0)
1223 msg0.add_sequence('foo')
1224 key0 = self._box.add(msg0)
1225 refmsg0 = self._box.get_message(key0)
1226
Benjamin Peterson21896a32010-03-21 22:03:03 +00001227 def test_issue7627(self):
1228 msg0 = mailbox.MHMessage(self._template % 0)
1229 key0 = self._box.add(msg0)
1230 self._box.lock()
1231 self._box.remove(key0)
1232 self._box.unlock()
1233
Thomas Wouters477c8d52006-05-27 19:21:47 +00001234 def test_pack(self):
1235 # Pack the contents of the mailbox
1236 msg0 = mailbox.MHMessage(self._template % 0)
1237 msg1 = mailbox.MHMessage(self._template % 1)
1238 msg2 = mailbox.MHMessage(self._template % 2)
1239 msg3 = mailbox.MHMessage(self._template % 3)
1240 msg0.set_sequences(['foo', 'unseen'])
1241 msg1.set_sequences(['foo'])
1242 msg2.set_sequences(['foo', 'flagged'])
1243 msg3.set_sequences(['foo', 'bar', 'replied'])
1244 key0 = self._box.add(msg0)
1245 key1 = self._box.add(msg1)
1246 key2 = self._box.add(msg2)
1247 key3 = self._box.add(msg3)
Guido van Rossumea834472007-07-27 05:17:50 +00001248 self.assertEqual(self._box.get_sequences(),
Thomas Wouters477c8d52006-05-27 19:21:47 +00001249 {'foo':[key0,key1,key2,key3], 'unseen':[key0],
1250 'flagged':[key2], 'bar':[key3], 'replied':[key3]})
1251 self._box.remove(key2)
Guido van Rossumea834472007-07-27 05:17:50 +00001252 self.assertEqual(self._box.get_sequences(),
Thomas Wouters477c8d52006-05-27 19:21:47 +00001253 {'foo':[key0,key1,key3], 'unseen':[key0], 'bar':[key3],
1254 'replied':[key3]})
1255 self._box.pack()
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00001256 self.assertEqual(self._box.keys(), [1, 2, 3])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001257 key0 = key0
1258 key1 = key0 + 1
1259 key2 = key1 + 1
Guido van Rossumea834472007-07-27 05:17:50 +00001260 self.assertEqual(self._box.get_sequences(),
Thomas Wouters477c8d52006-05-27 19:21:47 +00001261 {'foo':[1, 2, 3], 'unseen':[1], 'bar':[3], 'replied':[3]})
1262
Thomas Wouters89f507f2006-12-13 04:49:30 +00001263 # Test case for packing while holding the mailbox locked.
1264 key0 = self._box.add(msg1)
1265 key1 = self._box.add(msg1)
1266 key2 = self._box.add(msg1)
1267 key3 = self._box.add(msg1)
1268
1269 self._box.remove(key0)
1270 self._box.remove(key2)
1271 self._box.lock()
1272 self._box.pack()
1273 self._box.unlock()
Guido van Rossumea834472007-07-27 05:17:50 +00001274 self.assertEqual(self._box.get_sequences(),
Thomas Wouters89f507f2006-12-13 04:49:30 +00001275 {'foo':[1, 2, 3, 4, 5],
1276 'unseen':[1], 'bar':[3], 'replied':[3]})
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001277
Thomas Wouters477c8d52006-05-27 19:21:47 +00001278 def _get_lock_path(self):
1279 return os.path.join(self._path, '.mh_sequences.lock')
1280
1281
Petri Lehtinenf29435f2012-06-28 13:48:17 +03001282class TestBabyl(_TestSingleFile, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001283
1284 _factory = lambda self, path, factory=None: mailbox.Babyl(path, factory)
1285
R. David Murrayfc141142011-02-11 22:47:17 +00001286 def assertMailboxEmpty(self):
1287 with open(self._path) as f:
1288 self.assertEqual(f.readlines(), [])
1289
Thomas Wouters477c8d52006-05-27 19:21:47 +00001290 def tearDown(self):
Brett Cannon653238a2010-10-30 00:13:00 +00001291 super().tearDown()
Guido van Rossumc12a8132007-10-26 04:29:23 +00001292 self._box.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001293 self._delete_recursively(self._path)
1294 for lock_remnant in glob.glob(self._path + '.*'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001295 support.unlink(lock_remnant)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001296
1297 def test_labels(self):
1298 # Get labels from the mailbox
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001299 self.assertEqual(self._box.get_labels(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001300 msg0 = mailbox.BabylMessage(self._template % 0)
1301 msg0.add_label('foo')
1302 key0 = self._box.add(msg0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001303 self.assertEqual(self._box.get_labels(), ['foo'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001304 msg1 = mailbox.BabylMessage(self._template % 1)
1305 msg1.set_labels(['bar', 'answered', 'foo'])
1306 key1 = self._box.add(msg1)
Guido van Rossumea834472007-07-27 05:17:50 +00001307 self.assertEqual(set(self._box.get_labels()), set(['foo', 'bar']))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001308 msg0.set_labels(['blah', 'filed'])
1309 self._box[key0] = msg0
Guido van Rossumea834472007-07-27 05:17:50 +00001310 self.assertEqual(set(self._box.get_labels()),
Thomas Wouters477c8d52006-05-27 19:21:47 +00001311 set(['foo', 'bar', 'blah']))
1312 self._box.remove(key1)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001313 self.assertEqual(set(self._box.get_labels()), set(['blah']))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001314
1315
R David Murray05ff9902011-06-17 12:54:56 -04001316class FakeFileLikeObject:
1317
1318 def __init__(self):
1319 self.closed = False
1320
1321 def close(self):
1322 self.closed = True
1323
1324
1325class FakeMailBox(mailbox.Mailbox):
1326
1327 def __init__(self):
1328 mailbox.Mailbox.__init__(self, '', lambda file: None)
1329 self.files = [FakeFileLikeObject() for i in range(10)]
1330
1331 def get_file(self, key):
1332 return self.files[key]
1333
1334
1335class TestFakeMailBox(unittest.TestCase):
1336
1337 def test_closing_fd(self):
1338 box = FakeMailBox()
1339 for i in range(10):
1340 self.assertFalse(box.files[i].closed)
1341 for i in range(10):
1342 box[i]
1343 for i in range(10):
1344 self.assertTrue(box.files[i].closed)
1345
1346
R David Murray317c8d22012-04-08 16:46:18 -04001347class TestMessage(TestBase, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001348
1349 _factory = mailbox.Message # Overridden by subclasses to reuse tests
1350
1351 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001352 self._path = support.TESTFN
Thomas Wouters477c8d52006-05-27 19:21:47 +00001353
1354 def tearDown(self):
1355 self._delete_recursively(self._path)
1356
1357 def test_initialize_with_eMM(self):
Thomas Woutersb2137042007-02-01 18:02:27 +00001358 # Initialize based on email.message.Message instance
Thomas Wouters477c8d52006-05-27 19:21:47 +00001359 eMM = email.message_from_string(_sample_message)
1360 msg = self._factory(eMM)
1361 self._post_initialize_hook(msg)
1362 self._check_sample(msg)
1363
1364 def test_initialize_with_string(self):
1365 # Initialize based on string
1366 msg = self._factory(_sample_message)
1367 self._post_initialize_hook(msg)
1368 self._check_sample(msg)
1369
1370 def test_initialize_with_file(self):
1371 # Initialize based on contents of file
Brian Curtin5acec042010-10-13 02:29:46 +00001372 with open(self._path, 'w+') as f:
1373 f.write(_sample_message)
1374 f.seek(0)
1375 msg = self._factory(f)
1376 self._post_initialize_hook(msg)
1377 self._check_sample(msg)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001378
R. David Murrayb7deff12011-01-30 06:21:28 +00001379 def test_initialize_with_binary_file(self):
1380 # Initialize based on contents of binary file
1381 with open(self._path, 'wb+') as f:
1382 f.write(_bytes_sample_message)
1383 f.seek(0)
1384 msg = self._factory(f)
1385 self._post_initialize_hook(msg)
1386 self._check_sample(msg)
1387
Thomas Wouters477c8d52006-05-27 19:21:47 +00001388 def test_initialize_with_nothing(self):
1389 # Initialize without arguments
1390 msg = self._factory()
1391 self._post_initialize_hook(msg)
Ezio Melottie9615932010-01-24 19:26:24 +00001392 self.assertIsInstance(msg, email.message.Message)
1393 self.assertIsInstance(msg, mailbox.Message)
1394 self.assertIsInstance(msg, self._factory)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001395 self.assertEqual(msg.keys(), [])
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00001396 self.assertFalse(msg.is_multipart())
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001397 self.assertEqual(msg.get_payload(), None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001398
1399 def test_initialize_incorrectly(self):
1400 # Initialize with invalid argument
1401 self.assertRaises(TypeError, lambda: self._factory(object()))
1402
R David Murrayb019ee72012-04-08 22:36:07 -04001403 def test_all_eMM_attribues_exist(self):
1404 # Issue 12537
1405 eMM = email.message_from_string(_sample_message)
1406 msg = self._factory(_sample_message)
1407 for attr in eMM.__dict__:
1408 self.assertTrue(attr in msg.__dict__,
1409 '{} attribute does not exist'.format(attr))
1410
Thomas Wouters477c8d52006-05-27 19:21:47 +00001411 def test_become_message(self):
1412 # Take on the state of another message
1413 eMM = email.message_from_string(_sample_message)
1414 msg = self._factory()
1415 msg._become_message(eMM)
1416 self._check_sample(msg)
1417
1418 def test_explain_to(self):
1419 # Copy self's format-specific data to other message formats.
1420 # This test is superficial; better ones are in TestMessageConversion.
1421 msg = self._factory()
R David Murrayc988e242012-04-08 21:00:27 -04001422 for class_ in self.all_mailbox_types:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001423 other_msg = class_()
1424 msg._explain_to(other_msg)
Thomas Woutersb2137042007-02-01 18:02:27 +00001425 other_msg = email.message.Message()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001426 self.assertRaises(TypeError, lambda: msg._explain_to(other_msg))
1427
1428 def _post_initialize_hook(self, msg):
1429 # Overridden by subclasses to check extra things after initialization
1430 pass
1431
1432
R David Murray317c8d22012-04-08 16:46:18 -04001433class TestMaildirMessage(TestMessage, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001434
1435 _factory = mailbox.MaildirMessage
1436
1437 def _post_initialize_hook(self, msg):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001438 self.assertEqual(msg._subdir, 'new')
1439 self.assertEqual(msg._info, '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001440
1441 def test_subdir(self):
1442 # Use get_subdir() and set_subdir()
1443 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001444 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001445 msg.set_subdir('cur')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001446 self.assertEqual(msg.get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001447 msg.set_subdir('new')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001448 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001449 self.assertRaises(ValueError, lambda: msg.set_subdir('tmp'))
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001450 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001451 msg.set_subdir('new')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001452 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001453 self._check_sample(msg)
1454
1455 def test_flags(self):
1456 # Use get_flags(), set_flags(), add_flag(), remove_flag()
1457 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001458 self.assertEqual(msg.get_flags(), '')
1459 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001460 msg.set_flags('F')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001461 self.assertEqual(msg.get_subdir(), 'new')
1462 self.assertEqual(msg.get_flags(), 'F')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001463 msg.set_flags('SDTP')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001464 self.assertEqual(msg.get_flags(), 'DPST')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001465 msg.add_flag('FT')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001466 self.assertEqual(msg.get_flags(), 'DFPST')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001467 msg.remove_flag('TDRP')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001468 self.assertEqual(msg.get_flags(), 'FS')
1469 self.assertEqual(msg.get_subdir(), 'new')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001470 self._check_sample(msg)
1471
1472 def test_date(self):
1473 # Use get_date() and set_date()
1474 msg = mailbox.MaildirMessage(_sample_message)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00001475 self.assertLess(abs(msg.get_date() - time.time()), 60)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001476 msg.set_date(0.0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001477 self.assertEqual(msg.get_date(), 0.0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001478
1479 def test_info(self):
1480 # Use get_info() and set_info()
1481 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001482 self.assertEqual(msg.get_info(), '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001483 msg.set_info('1,foo=bar')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001484 self.assertEqual(msg.get_info(), '1,foo=bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001485 self.assertRaises(TypeError, lambda: msg.set_info(None))
1486 self._check_sample(msg)
1487
1488 def test_info_and_flags(self):
1489 # Test interaction of info and flag methods
1490 msg = mailbox.MaildirMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001491 self.assertEqual(msg.get_info(), '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001492 msg.set_flags('SF')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001493 self.assertEqual(msg.get_flags(), 'FS')
1494 self.assertEqual(msg.get_info(), '2,FS')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001495 msg.set_info('1,')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001496 self.assertEqual(msg.get_flags(), '')
1497 self.assertEqual(msg.get_info(), '1,')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001498 msg.remove_flag('RPT')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001499 self.assertEqual(msg.get_flags(), '')
1500 self.assertEqual(msg.get_info(), '1,')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001501 msg.add_flag('D')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001502 self.assertEqual(msg.get_flags(), 'D')
1503 self.assertEqual(msg.get_info(), '2,D')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001504 self._check_sample(msg)
1505
1506
R David Murray317c8d22012-04-08 16:46:18 -04001507class _TestMboxMMDFMessage:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001508
1509 _factory = mailbox._mboxMMDFMessage
1510
1511 def _post_initialize_hook(self, msg):
1512 self._check_from(msg)
1513
1514 def test_initialize_with_unixfrom(self):
1515 # Initialize with a message that already has a _unixfrom attribute
1516 msg = mailbox.Message(_sample_message)
1517 msg.set_unixfrom('From foo@bar blah')
1518 msg = mailbox.mboxMessage(msg)
Guido van Rossumea834472007-07-27 05:17:50 +00001519 self.assertEqual(msg.get_from(), 'foo@bar blah', msg.get_from())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001520
1521 def test_from(self):
1522 # Get and set "From " line
1523 msg = mailbox.mboxMessage(_sample_message)
1524 self._check_from(msg)
1525 msg.set_from('foo bar')
Guido van Rossumea834472007-07-27 05:17:50 +00001526 self.assertEqual(msg.get_from(), 'foo bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001527 msg.set_from('foo@bar', True)
1528 self._check_from(msg, 'foo@bar')
1529 msg.set_from('blah@temp', time.localtime())
1530 self._check_from(msg, 'blah@temp')
1531
1532 def test_flags(self):
1533 # Use get_flags(), set_flags(), add_flag(), remove_flag()
1534 msg = mailbox.mboxMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001535 self.assertEqual(msg.get_flags(), '')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001536 msg.set_flags('F')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001537 self.assertEqual(msg.get_flags(), 'F')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001538 msg.set_flags('XODR')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001539 self.assertEqual(msg.get_flags(), 'RODX')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001540 msg.add_flag('FA')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001541 self.assertEqual(msg.get_flags(), 'RODFAX')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001542 msg.remove_flag('FDXA')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001543 self.assertEqual(msg.get_flags(), 'RO')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001544 self._check_sample(msg)
1545
1546 def _check_from(self, msg, sender=None):
1547 # Check contents of "From " line
1548 if sender is None:
1549 sender = "MAILER-DAEMON"
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001550 self.assertTrue(re.match(sender + r" \w{3} \w{3} [\d ]\d [\d ]\d:\d{2}:"
Thomas Wouters477c8d52006-05-27 19:21:47 +00001551 r"\d{2} \d{4}", msg.get_from()) is not None)
1552
1553
R David Murray317c8d22012-04-08 16:46:18 -04001554class TestMboxMessage(_TestMboxMMDFMessage, TestMessage):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001555
1556 _factory = mailbox.mboxMessage
1557
1558
R David Murray317c8d22012-04-08 16:46:18 -04001559class TestMHMessage(TestMessage, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001560
1561 _factory = mailbox.MHMessage
1562
1563 def _post_initialize_hook(self, msg):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001564 self.assertEqual(msg._sequences, [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001565
1566 def test_sequences(self):
1567 # Get, set, join, and leave sequences
1568 msg = mailbox.MHMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001569 self.assertEqual(msg.get_sequences(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001570 msg.set_sequences(['foobar'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001571 self.assertEqual(msg.get_sequences(), ['foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001572 msg.set_sequences([])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001573 self.assertEqual(msg.get_sequences(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001574 msg.add_sequence('unseen')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001575 self.assertEqual(msg.get_sequences(), ['unseen'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001576 msg.add_sequence('flagged')
Guido van Rossumea834472007-07-27 05:17:50 +00001577 self.assertEqual(msg.get_sequences(), ['unseen', 'flagged'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001578 msg.add_sequence('flagged')
Guido van Rossumea834472007-07-27 05:17:50 +00001579 self.assertEqual(msg.get_sequences(), ['unseen', 'flagged'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001580 msg.remove_sequence('unseen')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001581 self.assertEqual(msg.get_sequences(), ['flagged'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001582 msg.add_sequence('foobar')
Guido van Rossumea834472007-07-27 05:17:50 +00001583 self.assertEqual(msg.get_sequences(), ['flagged', 'foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584 msg.remove_sequence('replied')
Guido van Rossumea834472007-07-27 05:17:50 +00001585 self.assertEqual(msg.get_sequences(), ['flagged', 'foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001586 msg.set_sequences(['foobar', 'replied'])
Guido van Rossumea834472007-07-27 05:17:50 +00001587 self.assertEqual(msg.get_sequences(), ['foobar', 'replied'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001588
1589
R David Murray317c8d22012-04-08 16:46:18 -04001590class TestBabylMessage(TestMessage, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001591
1592 _factory = mailbox.BabylMessage
1593
1594 def _post_initialize_hook(self, msg):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001595 self.assertEqual(msg._labels, [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001596
1597 def test_labels(self):
1598 # Get, set, join, and leave labels
1599 msg = mailbox.BabylMessage(_sample_message)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001600 self.assertEqual(msg.get_labels(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001601 msg.set_labels(['foobar'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001602 self.assertEqual(msg.get_labels(), ['foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001603 msg.set_labels([])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001604 self.assertEqual(msg.get_labels(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001605 msg.add_label('filed')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001606 self.assertEqual(msg.get_labels(), ['filed'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001607 msg.add_label('resent')
Guido van Rossumea834472007-07-27 05:17:50 +00001608 self.assertEqual(msg.get_labels(), ['filed', 'resent'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001609 msg.add_label('resent')
Guido van Rossumea834472007-07-27 05:17:50 +00001610 self.assertEqual(msg.get_labels(), ['filed', 'resent'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001611 msg.remove_label('filed')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001612 self.assertEqual(msg.get_labels(), ['resent'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001613 msg.add_label('foobar')
Guido van Rossumea834472007-07-27 05:17:50 +00001614 self.assertEqual(msg.get_labels(), ['resent', 'foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001615 msg.remove_label('unseen')
Guido van Rossumea834472007-07-27 05:17:50 +00001616 self.assertEqual(msg.get_labels(), ['resent', 'foobar'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001617 msg.set_labels(['foobar', 'answered'])
Guido van Rossumea834472007-07-27 05:17:50 +00001618 self.assertEqual(msg.get_labels(), ['foobar', 'answered'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001619
1620 def test_visible(self):
1621 # Get, set, and update visible headers
1622 msg = mailbox.BabylMessage(_sample_message)
1623 visible = msg.get_visible()
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001624 self.assertEqual(visible.keys(), [])
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00001625 self.assertIs(visible.get_payload(), None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001626 visible['User-Agent'] = 'FooBar 1.0'
1627 visible['X-Whatever'] = 'Blah'
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001628 self.assertEqual(msg.get_visible().keys(), [])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001629 msg.set_visible(visible)
1630 visible = msg.get_visible()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001631 self.assertTrue(visible.keys() == ['User-Agent', 'X-Whatever'])
1632 self.assertTrue(visible['User-Agent'] == 'FooBar 1.0')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001633 self.assertEqual(visible['X-Whatever'], 'Blah')
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00001634 self.assertIs(visible.get_payload(), None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001635 msg.update_visible()
Guido van Rossumea834472007-07-27 05:17:50 +00001636 self.assertEqual(visible.keys(), ['User-Agent', 'X-Whatever'])
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00001637 self.assertIs(visible.get_payload(), None)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001638 visible = msg.get_visible()
Guido van Rossumea834472007-07-27 05:17:50 +00001639 self.assertEqual(visible.keys(), ['User-Agent', 'Date', 'From', 'To',
1640 'Subject'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001641 for header in ('User-Agent', 'Date', 'From', 'To', 'Subject'):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001642 self.assertEqual(visible[header], msg[header])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001643
1644
R David Murray317c8d22012-04-08 16:46:18 -04001645class TestMMDFMessage(_TestMboxMMDFMessage, TestMessage):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001646
1647 _factory = mailbox.MMDFMessage
1648
1649
R David Murray317c8d22012-04-08 16:46:18 -04001650class TestMessageConversion(TestBase, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001651
1652 def test_plain_to_x(self):
1653 # Convert Message to all formats
R David Murrayc988e242012-04-08 21:00:27 -04001654 for class_ in self.all_mailbox_types:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001655 msg_plain = mailbox.Message(_sample_message)
1656 msg = class_(msg_plain)
1657 self._check_sample(msg)
1658
1659 def test_x_to_plain(self):
1660 # Convert all formats to Message
R David Murrayc988e242012-04-08 21:00:27 -04001661 for class_ in self.all_mailbox_types:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001662 msg = class_(_sample_message)
1663 msg_plain = mailbox.Message(msg)
1664 self._check_sample(msg_plain)
1665
R. David Murrayb7deff12011-01-30 06:21:28 +00001666 def test_x_from_bytes(self):
1667 # Convert all formats to Message
R David Murrayc988e242012-04-08 21:00:27 -04001668 for class_ in self.all_mailbox_types:
R. David Murrayb7deff12011-01-30 06:21:28 +00001669 msg = class_(_bytes_sample_message)
1670 self._check_sample(msg)
1671
Thomas Wouters477c8d52006-05-27 19:21:47 +00001672 def test_x_to_invalid(self):
1673 # Convert all formats to an invalid format
R David Murrayc988e242012-04-08 21:00:27 -04001674 for class_ in self.all_mailbox_types:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001675 self.assertRaises(TypeError, lambda: class_(False))
1676
R David Murrayb019ee72012-04-08 22:36:07 -04001677 def test_type_specific_attributes_removed_on_conversion(self):
1678 reference = {class_: class_(_sample_message).__dict__
1679 for class_ in self.all_mailbox_types}
1680 for class1 in self.all_mailbox_types:
1681 for class2 in self.all_mailbox_types:
1682 if class1 is class2:
1683 continue
1684 source = class1(_sample_message)
1685 target = class2(source)
1686 type_specific = [a for a in reference[class1]
1687 if a not in reference[class2]]
1688 for attr in type_specific:
1689 self.assertNotIn(attr, target.__dict__,
1690 "while converting {} to {}".format(class1, class2))
1691
Thomas Wouters477c8d52006-05-27 19:21:47 +00001692 def test_maildir_to_maildir(self):
1693 # Convert MaildirMessage to MaildirMessage
1694 msg_maildir = mailbox.MaildirMessage(_sample_message)
1695 msg_maildir.set_flags('DFPRST')
1696 msg_maildir.set_subdir('cur')
1697 date = msg_maildir.get_date()
1698 msg = mailbox.MaildirMessage(msg_maildir)
1699 self._check_sample(msg)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001700 self.assertEqual(msg.get_flags(), 'DFPRST')
1701 self.assertEqual(msg.get_subdir(), 'cur')
1702 self.assertEqual(msg.get_date(), date)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001703
1704 def test_maildir_to_mboxmmdf(self):
1705 # Convert MaildirMessage to mboxmessage and MMDFMessage
1706 pairs = (('D', ''), ('F', 'F'), ('P', ''), ('R', 'A'), ('S', 'R'),
1707 ('T', 'D'), ('DFPRST', 'RDFA'))
1708 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1709 msg_maildir = mailbox.MaildirMessage(_sample_message)
1710 msg_maildir.set_date(0.0)
1711 for setting, result in pairs:
1712 msg_maildir.set_flags(setting)
1713 msg = class_(msg_maildir)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001714 self.assertEqual(msg.get_flags(), result)
Guido van Rossumea834472007-07-27 05:17:50 +00001715 self.assertEqual(msg.get_from(), 'MAILER-DAEMON %s' %
Thomas Wouters477c8d52006-05-27 19:21:47 +00001716 time.asctime(time.gmtime(0.0)))
1717 msg_maildir.set_subdir('cur')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001718 self.assertEqual(class_(msg_maildir).get_flags(), 'RODFA')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001719
1720 def test_maildir_to_mh(self):
1721 # Convert MaildirMessage to MHMessage
1722 msg_maildir = mailbox.MaildirMessage(_sample_message)
1723 pairs = (('D', ['unseen']), ('F', ['unseen', 'flagged']),
1724 ('P', ['unseen']), ('R', ['unseen', 'replied']), ('S', []),
1725 ('T', ['unseen']), ('DFPRST', ['replied', 'flagged']))
1726 for setting, result in pairs:
1727 msg_maildir.set_flags(setting)
Guido van Rossumea834472007-07-27 05:17:50 +00001728 self.assertEqual(mailbox.MHMessage(msg_maildir).get_sequences(),
1729 result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001730
1731 def test_maildir_to_babyl(self):
1732 # Convert MaildirMessage to Babyl
1733 msg_maildir = mailbox.MaildirMessage(_sample_message)
1734 pairs = (('D', ['unseen']), ('F', ['unseen']),
1735 ('P', ['unseen', 'forwarded']), ('R', ['unseen', 'answered']),
1736 ('S', []), ('T', ['unseen', 'deleted']),
1737 ('DFPRST', ['deleted', 'answered', 'forwarded']))
1738 for setting, result in pairs:
1739 msg_maildir.set_flags(setting)
Guido van Rossumea834472007-07-27 05:17:50 +00001740 self.assertEqual(mailbox.BabylMessage(msg_maildir).get_labels(),
1741 result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001742
1743 def test_mboxmmdf_to_maildir(self):
1744 # Convert mboxMessage and MMDFMessage to MaildirMessage
1745 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1746 msg_mboxMMDF = class_(_sample_message)
1747 msg_mboxMMDF.set_from('foo@bar', time.gmtime(0.0))
1748 pairs = (('R', 'S'), ('O', ''), ('D', 'T'), ('F', 'F'), ('A', 'R'),
1749 ('RODFA', 'FRST'))
1750 for setting, result in pairs:
1751 msg_mboxMMDF.set_flags(setting)
1752 msg = mailbox.MaildirMessage(msg_mboxMMDF)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001753 self.assertEqual(msg.get_flags(), result)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00001754 self.assertEqual(msg.get_date(), 0.0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001755 msg_mboxMMDF.set_flags('O')
Guido van Rossumea834472007-07-27 05:17:50 +00001756 self.assertEqual(mailbox.MaildirMessage(msg_mboxMMDF).get_subdir(),
1757 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001758
1759 def test_mboxmmdf_to_mboxmmdf(self):
1760 # Convert mboxMessage and MMDFMessage to mboxMessage and MMDFMessage
1761 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1762 msg_mboxMMDF = class_(_sample_message)
1763 msg_mboxMMDF.set_flags('RODFA')
1764 msg_mboxMMDF.set_from('foo@bar')
1765 for class2_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1766 msg2 = class2_(msg_mboxMMDF)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001767 self.assertEqual(msg2.get_flags(), 'RODFA')
1768 self.assertEqual(msg2.get_from(), 'foo@bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001769
1770 def test_mboxmmdf_to_mh(self):
1771 # Convert mboxMessage and MMDFMessage to MHMessage
1772 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1773 msg_mboxMMDF = class_(_sample_message)
1774 pairs = (('R', []), ('O', ['unseen']), ('D', ['unseen']),
1775 ('F', ['unseen', 'flagged']),
1776 ('A', ['unseen', 'replied']),
1777 ('RODFA', ['replied', 'flagged']))
1778 for setting, result in pairs:
1779 msg_mboxMMDF.set_flags(setting)
Guido van Rossumea834472007-07-27 05:17:50 +00001780 self.assertEqual(mailbox.MHMessage(msg_mboxMMDF).get_sequences(),
1781 result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001782
1783 def test_mboxmmdf_to_babyl(self):
1784 # Convert mboxMessage and MMDFMessage to BabylMessage
1785 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1786 msg = class_(_sample_message)
1787 pairs = (('R', []), ('O', ['unseen']),
1788 ('D', ['unseen', 'deleted']), ('F', ['unseen']),
1789 ('A', ['unseen', 'answered']),
1790 ('RODFA', ['deleted', 'answered']))
1791 for setting, result in pairs:
1792 msg.set_flags(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001793 self.assertEqual(mailbox.BabylMessage(msg).get_labels(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001794
1795 def test_mh_to_maildir(self):
1796 # Convert MHMessage to MaildirMessage
1797 pairs = (('unseen', ''), ('replied', 'RS'), ('flagged', 'FS'))
1798 for setting, result in pairs:
1799 msg = mailbox.MHMessage(_sample_message)
1800 msg.add_sequence(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001801 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), result)
1802 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001803 msg = mailbox.MHMessage(_sample_message)
1804 msg.add_sequence('unseen')
1805 msg.add_sequence('replied')
1806 msg.add_sequence('flagged')
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001807 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), 'FR')
1808 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001809
1810 def test_mh_to_mboxmmdf(self):
1811 # Convert MHMessage to mboxMessage and MMDFMessage
1812 pairs = (('unseen', 'O'), ('replied', 'ROA'), ('flagged', 'ROF'))
1813 for setting, result in pairs:
1814 msg = mailbox.MHMessage(_sample_message)
1815 msg.add_sequence(setting)
1816 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001817 self.assertEqual(class_(msg).get_flags(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001818 msg = mailbox.MHMessage(_sample_message)
1819 msg.add_sequence('unseen')
1820 msg.add_sequence('replied')
1821 msg.add_sequence('flagged')
1822 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001823 self.assertEqual(class_(msg).get_flags(), 'OFA')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001824
1825 def test_mh_to_mh(self):
1826 # Convert MHMessage to MHMessage
1827 msg = mailbox.MHMessage(_sample_message)
1828 msg.add_sequence('unseen')
1829 msg.add_sequence('replied')
1830 msg.add_sequence('flagged')
Guido van Rossumea834472007-07-27 05:17:50 +00001831 self.assertEqual(mailbox.MHMessage(msg).get_sequences(),
1832 ['unseen', 'replied', 'flagged'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001833
1834 def test_mh_to_babyl(self):
1835 # Convert MHMessage to BabylMessage
1836 pairs = (('unseen', ['unseen']), ('replied', ['answered']),
1837 ('flagged', []))
1838 for setting, result in pairs:
1839 msg = mailbox.MHMessage(_sample_message)
1840 msg.add_sequence(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001841 self.assertEqual(mailbox.BabylMessage(msg).get_labels(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001842 msg = mailbox.MHMessage(_sample_message)
1843 msg.add_sequence('unseen')
1844 msg.add_sequence('replied')
1845 msg.add_sequence('flagged')
Guido van Rossumea834472007-07-27 05:17:50 +00001846 self.assertEqual(mailbox.BabylMessage(msg).get_labels(),
1847 ['unseen', 'answered'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001848
1849 def test_babyl_to_maildir(self):
1850 # Convert BabylMessage to MaildirMessage
1851 pairs = (('unseen', ''), ('deleted', 'ST'), ('filed', 'S'),
1852 ('answered', 'RS'), ('forwarded', 'PS'), ('edited', 'S'),
1853 ('resent', 'PS'))
1854 for setting, result in pairs:
1855 msg = mailbox.BabylMessage(_sample_message)
1856 msg.add_label(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001857 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), result)
1858 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001859 msg = mailbox.BabylMessage(_sample_message)
1860 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1861 'edited', 'resent'):
1862 msg.add_label(label)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001863 self.assertEqual(mailbox.MaildirMessage(msg).get_flags(), 'PRT')
1864 self.assertEqual(mailbox.MaildirMessage(msg).get_subdir(), 'cur')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001865
1866 def test_babyl_to_mboxmmdf(self):
1867 # Convert BabylMessage to mboxMessage and MMDFMessage
1868 pairs = (('unseen', 'O'), ('deleted', 'ROD'), ('filed', 'RO'),
1869 ('answered', 'ROA'), ('forwarded', 'RO'), ('edited', 'RO'),
1870 ('resent', 'RO'))
1871 for setting, result in pairs:
1872 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
1873 msg = mailbox.BabylMessage(_sample_message)
1874 msg.add_label(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001875 self.assertEqual(class_(msg).get_flags(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001876 msg = mailbox.BabylMessage(_sample_message)
1877 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1878 'edited', 'resent'):
1879 msg.add_label(label)
1880 for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001881 self.assertEqual(class_(msg).get_flags(), 'ODA')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001882
1883 def test_babyl_to_mh(self):
1884 # Convert BabylMessage to MHMessage
1885 pairs = (('unseen', ['unseen']), ('deleted', []), ('filed', []),
1886 ('answered', ['replied']), ('forwarded', []), ('edited', []),
1887 ('resent', []))
1888 for setting, result in pairs:
1889 msg = mailbox.BabylMessage(_sample_message)
1890 msg.add_label(setting)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001891 self.assertEqual(mailbox.MHMessage(msg).get_sequences(), result)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001892 msg = mailbox.BabylMessage(_sample_message)
1893 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1894 'edited', 'resent'):
1895 msg.add_label(label)
Guido van Rossumea834472007-07-27 05:17:50 +00001896 self.assertEqual(mailbox.MHMessage(msg).get_sequences(),
1897 ['unseen', 'replied'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001898
1899 def test_babyl_to_babyl(self):
1900 # Convert BabylMessage to BabylMessage
1901 msg = mailbox.BabylMessage(_sample_message)
1902 msg.update_visible()
1903 for label in ('unseen', 'deleted', 'filed', 'answered', 'forwarded',
1904 'edited', 'resent'):
1905 msg.add_label(label)
1906 msg2 = mailbox.BabylMessage(msg)
Guido van Rossumea834472007-07-27 05:17:50 +00001907 self.assertEqual(msg2.get_labels(), ['unseen', 'deleted', 'filed',
1908 'answered', 'forwarded', 'edited',
1909 'resent'])
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001910 self.assertEqual(msg.get_visible().keys(), msg2.get_visible().keys())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001911 for key in msg.get_visible().keys():
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001912 self.assertEqual(msg.get_visible()[key], msg2.get_visible()[key])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001913
1914
1915class TestProxyFileBase(TestBase):
1916
1917 def _test_read(self, proxy):
1918 # Read by byte
1919 proxy.seek(0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001920 self.assertEqual(proxy.read(), b'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001921 proxy.seek(1)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001922 self.assertEqual(proxy.read(), b'ar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001923 proxy.seek(0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001924 self.assertEqual(proxy.read(2), b'ba')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001925 proxy.seek(1)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001926 self.assertEqual(proxy.read(-1), b'ar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001927 proxy.seek(2)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001928 self.assertEqual(proxy.read(1000), b'r')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001929
1930 def _test_readline(self, proxy):
1931 # Read by line
Guido van Rossum98297ee2007-11-06 21:34:58 +00001932 linesep = os.linesep.encode()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001933 proxy.seek(0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001934 self.assertEqual(proxy.readline(), b'foo' + linesep)
1935 self.assertEqual(proxy.readline(), b'bar' + linesep)
1936 self.assertEqual(proxy.readline(), b'fred' + linesep)
1937 self.assertEqual(proxy.readline(), b'bob')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001938 proxy.seek(2)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001939 self.assertEqual(proxy.readline(), b'o' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001940 proxy.seek(6 + 2 * len(os.linesep))
Guido van Rossum98297ee2007-11-06 21:34:58 +00001941 self.assertEqual(proxy.readline(), b'fred' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001942 proxy.seek(6 + 2 * len(os.linesep))
Guido van Rossum98297ee2007-11-06 21:34:58 +00001943 self.assertEqual(proxy.readline(2), b'fr')
1944 self.assertEqual(proxy.readline(-10), b'ed' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001945
1946 def _test_readlines(self, proxy):
1947 # Read multiple lines
Guido van Rossum98297ee2007-11-06 21:34:58 +00001948 linesep = os.linesep.encode()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001949 proxy.seek(0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001950 self.assertEqual(proxy.readlines(), [b'foo' + linesep,
1951 b'bar' + linesep,
1952 b'fred' + linesep, b'bob'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001953 proxy.seek(0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001954 self.assertEqual(proxy.readlines(2), [b'foo' + linesep])
1955 proxy.seek(3 + len(linesep))
1956 self.assertEqual(proxy.readlines(4 + len(linesep)),
1957 [b'bar' + linesep, b'fred' + linesep])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001958 proxy.seek(3)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001959 self.assertEqual(proxy.readlines(1000), [linesep, b'bar' + linesep,
1960 b'fred' + linesep, b'bob'])
Thomas Wouters477c8d52006-05-27 19:21:47 +00001961
1962 def _test_iteration(self, proxy):
1963 # Iterate by line
Guido van Rossum98297ee2007-11-06 21:34:58 +00001964 linesep = os.linesep.encode()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001965 proxy.seek(0)
1966 iterator = iter(proxy)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001967 self.assertEqual(next(iterator), b'foo' + linesep)
1968 self.assertEqual(next(iterator), b'bar' + linesep)
1969 self.assertEqual(next(iterator), b'fred' + linesep)
1970 self.assertEqual(next(iterator), b'bob')
Georg Brandla18af4e2007-04-21 15:47:16 +00001971 self.assertRaises(StopIteration, next, iterator)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001972
1973 def _test_seek_and_tell(self, proxy):
1974 # Seek and use tell to check position
Guido van Rossum98297ee2007-11-06 21:34:58 +00001975 linesep = os.linesep.encode()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001976 proxy.seek(3)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001977 self.assertEqual(proxy.tell(), 3)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001978 self.assertEqual(proxy.read(len(linesep)), linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001979 proxy.seek(2, 1)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001980 self.assertEqual(proxy.read(1 + len(linesep)), b'r' + linesep)
1981 proxy.seek(-3 - len(linesep), 2)
1982 self.assertEqual(proxy.read(3), b'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001983 proxy.seek(2, 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001984 self.assertEqual(proxy.read(), b'o' + linesep + b'bar' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001985 proxy.seek(100)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001986 self.assertFalse(proxy.read())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001987
1988 def _test_close(self, proxy):
1989 # Close a file
R David Murrayc88bce12011-06-17 22:24:05 -04001990 self.assertFalse(proxy.closed)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001991 proxy.close()
R David Murrayc88bce12011-06-17 22:24:05 -04001992 self.assertTrue(proxy.closed)
1993 # Issue 11700 subsequent closes should be a no-op.
1994 proxy.close()
1995 self.assertTrue(proxy.closed)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001996
1997
R David Murray317c8d22012-04-08 16:46:18 -04001998class TestProxyFile(TestProxyFileBase, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001999
2000 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002001 self._path = support.TESTFN
Thomas Wouters477c8d52006-05-27 19:21:47 +00002002 self._file = open(self._path, 'wb+')
2003
2004 def tearDown(self):
2005 self._file.close()
2006 self._delete_recursively(self._path)
2007
2008 def test_initialize(self):
2009 # Initialize and check position
Neal Norwitz9a923102007-08-30 06:20:05 +00002010 self._file.write(b'foo')
Thomas Wouters477c8d52006-05-27 19:21:47 +00002011 pos = self._file.tell()
2012 proxy0 = mailbox._ProxyFile(self._file)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00002013 self.assertEqual(proxy0.tell(), pos)
2014 self.assertEqual(self._file.tell(), pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002015 proxy1 = mailbox._ProxyFile(self._file, 0)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00002016 self.assertEqual(proxy1.tell(), 0)
2017 self.assertEqual(self._file.tell(), pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002018
2019 def test_read(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002020 self._file.write(b'bar')
Thomas Wouters477c8d52006-05-27 19:21:47 +00002021 self._test_read(mailbox._ProxyFile(self._file))
2022
2023 def test_readline(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002024 self._file.write(bytes('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
2025 os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002026 self._test_readline(mailbox._ProxyFile(self._file))
2027
2028 def test_readlines(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002029 self._file.write(bytes('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
2030 os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002031 self._test_readlines(mailbox._ProxyFile(self._file))
2032
2033 def test_iteration(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002034 self._file.write(bytes('foo%sbar%sfred%sbob' % (os.linesep, os.linesep,
2035 os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002036 self._test_iteration(mailbox._ProxyFile(self._file))
2037
2038 def test_seek_and_tell(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002039 self._file.write(bytes('foo%sbar%s' % (os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002040 self._test_seek_and_tell(mailbox._ProxyFile(self._file))
2041
2042 def test_close(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002043 self._file.write(bytes('foo%sbar%s' % (os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002044 self._test_close(mailbox._ProxyFile(self._file))
2045
2046
R David Murray317c8d22012-04-08 16:46:18 -04002047class TestPartialFile(TestProxyFileBase, unittest.TestCase):
Thomas Wouters477c8d52006-05-27 19:21:47 +00002048
2049 def setUp(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002050 self._path = support.TESTFN
Thomas Wouters477c8d52006-05-27 19:21:47 +00002051 self._file = open(self._path, 'wb+')
2052
2053 def tearDown(self):
2054 self._file.close()
2055 self._delete_recursively(self._path)
2056
2057 def test_initialize(self):
2058 # Initialize and check position
Neal Norwitz9a923102007-08-30 06:20:05 +00002059 self._file.write(bytes('foo' + os.linesep + 'bar', 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002060 pos = self._file.tell()
2061 proxy = mailbox._PartialFile(self._file, 2, 5)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00002062 self.assertEqual(proxy.tell(), 0)
2063 self.assertEqual(self._file.tell(), pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002064
2065 def test_read(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002066 self._file.write(bytes('***bar***', 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002067 self._test_read(mailbox._PartialFile(self._file, 3, 6))
2068
2069 def test_readline(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002070 self._file.write(bytes('!!!!!foo%sbar%sfred%sbob!!!!!' %
2071 (os.linesep, os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002072 self._test_readline(mailbox._PartialFile(self._file, 5,
2073 18 + 3 * len(os.linesep)))
2074
2075 def test_readlines(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002076 self._file.write(bytes('foo%sbar%sfred%sbob?????' %
2077 (os.linesep, os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002078 self._test_readlines(mailbox._PartialFile(self._file, 0,
2079 13 + 3 * len(os.linesep)))
2080
2081 def test_iteration(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002082 self._file.write(bytes('____foo%sbar%sfred%sbob####' %
2083 (os.linesep, os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002084 self._test_iteration(mailbox._PartialFile(self._file, 4,
2085 17 + 3 * len(os.linesep)))
2086
2087 def test_seek_and_tell(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002088 self._file.write(bytes('(((foo%sbar%s$$$' % (os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002089 self._test_seek_and_tell(mailbox._PartialFile(self._file, 3,
2090 9 + 2 * len(os.linesep)))
2091
2092 def test_close(self):
Neal Norwitz9a923102007-08-30 06:20:05 +00002093 self._file.write(bytes('&foo%sbar%s^' % (os.linesep, os.linesep), 'ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00002094 self._test_close(mailbox._PartialFile(self._file, 1,
2095 6 + 3 * len(os.linesep)))
2096
2097
2098## Start: tests from the original module (for backward compatibility).
2099
Skip Montanaro5253da12004-07-24 19:56:03 +00002100FROM_ = "From some.body@dummy.domain Sat Jul 24 13:43:35 2004\n"
Fred Drakec02bc3e2001-05-21 20:23:21 +00002101DUMMY_MESSAGE = """\
2102From: some.body@dummy.domain
2103To: me@my.domain
Skip Montanaro5253da12004-07-24 19:56:03 +00002104Subject: Simple Test
Fred Drakec02bc3e2001-05-21 20:23:21 +00002105
2106This is a dummy message.
2107"""
2108
Fred Drakec02bc3e2001-05-21 20:23:21 +00002109class MaildirTestCase(unittest.TestCase):
2110
2111 def setUp(self):
2112 # create a new maildir mailbox to work with:
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002113 self._dir = support.TESTFN
Vinay Sajipf9596182012-03-02 01:01:13 +00002114 if os.path.isdir(self._dir):
2115 shutil.rmtree(self._dir)
2116 elif os.path.isfile(self._dir):
2117 os.unlink(self._dir)
Fred Drakec02bc3e2001-05-21 20:23:21 +00002118 os.mkdir(self._dir)
2119 os.mkdir(os.path.join(self._dir, "cur"))
2120 os.mkdir(os.path.join(self._dir, "tmp"))
2121 os.mkdir(os.path.join(self._dir, "new"))
2122 self._counter = 1
2123 self._msgfiles = []
2124
2125 def tearDown(self):
Guido van Rossumc1f779c2007-07-03 08:25:58 +00002126 list(map(os.unlink, self._msgfiles))
Fred Drakec02bc3e2001-05-21 20:23:21 +00002127 os.rmdir(os.path.join(self._dir, "cur"))
2128 os.rmdir(os.path.join(self._dir, "tmp"))
2129 os.rmdir(os.path.join(self._dir, "new"))
2130 os.rmdir(self._dir)
2131
Skip Montanaro5253da12004-07-24 19:56:03 +00002132 def createMessage(self, dir, mbox=False):
Jack Jansen97df7b62001-06-19 20:20:05 +00002133 t = int(time.time() % 1000000)
Fred Drakec02bc3e2001-05-21 20:23:21 +00002134 pid = self._counter
2135 self._counter += 1
Skip Montanaro7a98be22007-08-16 14:35:24 +00002136 filename = ".".join((str(t), str(pid), "myhostname", "mydomain"))
Fred Drakec02bc3e2001-05-21 20:23:21 +00002137 tmpname = os.path.join(self._dir, "tmp", filename)
2138 newname = os.path.join(self._dir, dir, filename)
Brian Curtin5acec042010-10-13 02:29:46 +00002139 with open(tmpname, "w") as fp:
2140 self._msgfiles.append(tmpname)
2141 if mbox:
2142 fp.write(FROM_)
2143 fp.write(DUMMY_MESSAGE)
Tim Peters6626c1f2001-05-22 16:29:01 +00002144 if hasattr(os, "link"):
2145 os.link(tmpname, newname)
2146 else:
Brian Curtin5acec042010-10-13 02:29:46 +00002147 with open(newname, "w") as fp:
2148 fp.write(DUMMY_MESSAGE)
Fred Drakec02bc3e2001-05-21 20:23:21 +00002149 self._msgfiles.append(newname)
Skip Montanaro5253da12004-07-24 19:56:03 +00002150 return tmpname
Fred Drakec02bc3e2001-05-21 20:23:21 +00002151
2152 def test_empty_maildir(self):
2153 """Test an empty maildir mailbox"""
2154 # Test for regression on bug #117490:
2155 # Make sure the boxes attribute actually gets set.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002156 self.mbox = mailbox.Maildir(support.TESTFN)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002157 #self.assertTrue(hasattr(self.mbox, "boxes"))
Guido van Rossume61fd5b2007-07-11 12:20:59 +00002158 #self.assertEqual(len(self.mbox.boxes), 0)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00002159 self.assertIs(self.mbox.next(), None)
2160 self.assertIs(self.mbox.next(), None)
Fred Drakec02bc3e2001-05-21 20:23:21 +00002161
2162 def test_nonempty_maildir_cur(self):
2163 self.createMessage("cur")
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002164 self.mbox = mailbox.Maildir(support.TESTFN)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00002165 #self.assertEqual(len(self.mbox.boxes), 1)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00002166 self.assertIsNot(self.mbox.next(), None)
2167 self.assertIs(self.mbox.next(), None)
2168 self.assertIs(self.mbox.next(), None)
Fred Drakec02bc3e2001-05-21 20:23:21 +00002169
2170 def test_nonempty_maildir_new(self):
2171 self.createMessage("new")
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002172 self.mbox = mailbox.Maildir(support.TESTFN)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00002173 #self.assertEqual(len(self.mbox.boxes), 1)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00002174 self.assertIsNot(self.mbox.next(), None)
2175 self.assertIs(self.mbox.next(), None)
2176 self.assertIs(self.mbox.next(), None)
Fred Drakec02bc3e2001-05-21 20:23:21 +00002177
2178 def test_nonempty_maildir_both(self):
2179 self.createMessage("cur")
2180 self.createMessage("new")
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002181 self.mbox = mailbox.Maildir(support.TESTFN)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00002182 #self.assertEqual(len(self.mbox.boxes), 2)
Alexandre Vassalottib27a1d22009-07-22 23:27:17 +00002183 self.assertIsNot(self.mbox.next(), None)
2184 self.assertIsNot(self.mbox.next(), None)
2185 self.assertIs(self.mbox.next(), None)
2186 self.assertIs(self.mbox.next(), None)
Fred Drake0aaed272000-10-23 13:39:15 +00002187
Georg Brandledb978f2008-05-11 08:59:40 +00002188## End: tests from the original module (for backward compatibility).
Thomas Wouters477c8d52006-05-27 19:21:47 +00002189
2190
2191_sample_message = """\
2192Return-Path: <gkj@gregorykjohnson.com>
2193X-Original-To: gkj+person@localhost
2194Delivered-To: gkj+person@localhost
2195Received: from localhost (localhost [127.0.0.1])
2196 by andy.gregorykjohnson.com (Postfix) with ESMTP id 356ED9DD17
2197 for <gkj+person@localhost>; Wed, 13 Jul 2005 17:23:16 -0400 (EDT)
2198Delivered-To: gkj@sundance.gregorykjohnson.com
2199Received: from localhost [127.0.0.1]
2200 by localhost with POP3 (fetchmail-6.2.5)
2201 for gkj+person@localhost (single-drop); Wed, 13 Jul 2005 17:23:16 -0400 (EDT)
2202Received: from andy.gregorykjohnson.com (andy.gregorykjohnson.com [64.32.235.228])
2203 by sundance.gregorykjohnson.com (Postfix) with ESMTP id 5B056316746
2204 for <gkj@gregorykjohnson.com>; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)
2205Received: by andy.gregorykjohnson.com (Postfix, from userid 1000)
2206 id 490CD9DD17; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)
2207Date: Wed, 13 Jul 2005 17:23:11 -0400
2208From: "Gregory K. Johnson" <gkj@gregorykjohnson.com>
2209To: gkj@gregorykjohnson.com
2210Subject: Sample message
2211Message-ID: <20050713212311.GC4701@andy.gregorykjohnson.com>
2212Mime-Version: 1.0
2213Content-Type: multipart/mixed; boundary="NMuMz9nt05w80d4+"
2214Content-Disposition: inline
2215User-Agent: Mutt/1.5.9i
2216
2217
2218--NMuMz9nt05w80d4+
2219Content-Type: text/plain; charset=us-ascii
2220Content-Disposition: inline
2221
2222This is a sample message.
2223
2224--
2225Gregory K. Johnson
2226
2227--NMuMz9nt05w80d4+
2228Content-Type: application/octet-stream
2229Content-Disposition: attachment; filename="text.gz"
2230Content-Transfer-Encoding: base64
2231
2232H4sICM2D1UIAA3RleHQAC8nILFYAokSFktSKEoW0zJxUPa7wzJIMhZLyfIWczLzUYj0uAHTs
22333FYlAAAA
2234
2235--NMuMz9nt05w80d4+--
2236"""
2237
R. David Murrayb7deff12011-01-30 06:21:28 +00002238_bytes_sample_message = _sample_message.encode('ascii')
2239
Thomas Wouters477c8d52006-05-27 19:21:47 +00002240_sample_headers = {
2241 "Return-Path":"<gkj@gregorykjohnson.com>",
2242 "X-Original-To":"gkj+person@localhost",
2243 "Delivered-To":"gkj+person@localhost",
2244 "Received":"""from localhost (localhost [127.0.0.1])
2245 by andy.gregorykjohnson.com (Postfix) with ESMTP id 356ED9DD17
2246 for <gkj+person@localhost>; Wed, 13 Jul 2005 17:23:16 -0400 (EDT)""",
2247 "Delivered-To":"gkj@sundance.gregorykjohnson.com",
2248 "Received":"""from localhost [127.0.0.1]
2249 by localhost with POP3 (fetchmail-6.2.5)
2250 for gkj+person@localhost (single-drop); Wed, 13 Jul 2005 17:23:16 -0400 (EDT)""",
2251 "Received":"""from andy.gregorykjohnson.com (andy.gregorykjohnson.com [64.32.235.228])
2252 by sundance.gregorykjohnson.com (Postfix) with ESMTP id 5B056316746
2253 for <gkj@gregorykjohnson.com>; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)""",
2254 "Received":"""by andy.gregorykjohnson.com (Postfix, from userid 1000)
2255 id 490CD9DD17; Wed, 13 Jul 2005 17:23:11 -0400 (EDT)""",
2256 "Date":"Wed, 13 Jul 2005 17:23:11 -0400",
2257 "From":""""Gregory K. Johnson" <gkj@gregorykjohnson.com>""",
2258 "To":"gkj@gregorykjohnson.com",
2259 "Subject":"Sample message",
2260 "Mime-Version":"1.0",
2261 "Content-Type":"""multipart/mixed; boundary="NMuMz9nt05w80d4+\"""",
2262 "Content-Disposition":"inline",
2263 "User-Agent": "Mutt/1.5.9i" }
2264
2265_sample_payloads = ("""This is a sample message.
2266
2267--
2268Gregory K. Johnson
2269""",
2270"""H4sICM2D1UIAA3RleHQAC8nILFYAokSFktSKEoW0zJxUPa7wzJIMhZLyfIWczLzUYj0uAHTs
22713FYlAAAA
2272""")
Fred Drake0aaed272000-10-23 13:39:15 +00002273
Fred Drakec02bc3e2001-05-21 20:23:21 +00002274
Fred Drake2e2be372001-09-20 21:33:42 +00002275def test_main():
Thomas Wouters477c8d52006-05-27 19:21:47 +00002276 tests = (TestMailboxSuperclass, TestMaildir, TestMbox, TestMMDF, TestMH,
2277 TestBabyl, TestMessage, TestMaildirMessage, TestMboxMessage,
2278 TestMHMessage, TestBabylMessage, TestMMDFMessage,
2279 TestMessageConversion, TestProxyFile, TestPartialFile,
R David Murray05ff9902011-06-17 12:54:56 -04002280 MaildirTestCase, TestFakeMailBox)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002281 support.run_unittest(*tests)
2282 support.reap_children()
Fred Drake2e2be372001-09-20 21:33:42 +00002283
2284
Thomas Wouters477c8d52006-05-27 19:21:47 +00002285if __name__ == '__main__':
Fred Drake2e2be372001-09-20 21:33:42 +00002286 test_main()