blob: 6fecaf565b295365b0cc5b1d778a5d52ccfc4f33 [file] [log] [blame]
Georg Brandl31631792006-10-29 19:13:40 +00001from test.test_support import TESTFN, run_unittest
Andrew M. Kuchlinge81b9cf2000-03-30 21:15:29 +00002import mmap
Georg Brandl31631792006-10-29 19:13:40 +00003import unittest
Fred Drake62787992001-05-11 14:29:21 +00004import os, re
Andrew M. Kuchlinge81b9cf2000-03-30 21:15:29 +00005
6PAGESIZE = mmap.PAGESIZE
7
Georg Brandl31631792006-10-29 19:13:40 +00008class MmapTests(unittest.TestCase):
Fred Drake004d5e62000-10-23 17:22:08 +00009
Georg Brandl31631792006-10-29 19:13:40 +000010 def setUp(self):
11 if os.path.exists(TESTFN):
12 os.unlink(TESTFN)
Fred Drake004d5e62000-10-23 17:22:08 +000013
Georg Brandl31631792006-10-29 19:13:40 +000014 def tearDown(self):
Tim Petersfd692082001-05-10 20:03:04 +000015 try:
Fred Drake62787992001-05-11 14:29:21 +000016 os.unlink(TESTFN)
Tim Petersfd692082001-05-10 20:03:04 +000017 except OSError:
18 pass
19
Georg Brandl31631792006-10-29 19:13:40 +000020 def test_basic(self):
21 # Test mmap module on Unix systems and Windows
22
23 # Create a file to be mmap'ed.
24 f = open(TESTFN, 'w+')
25 try:
26 # Write 2 pages worth of data to the file
27 f.write('\0'* PAGESIZE)
28 f.write('foo')
29 f.write('\0'* (PAGESIZE-3) )
30 f.flush()
31 m = mmap.mmap(f.fileno(), 2 * PAGESIZE)
32 f.close()
33
34 # Simple sanity checks
35
36 tp = str(type(m)) # SF bug 128713: segfaulted on Linux
37 self.assertEqual(m.find('foo'), PAGESIZE)
38
39 self.assertEqual(len(m), 2*PAGESIZE)
40
41 self.assertEqual(m[0], '\0')
42 self.assertEqual(m[0:3], '\0\0\0')
43
44 # Modify the file's content
45 m[0] = '3'
46 m[PAGESIZE +3: PAGESIZE +3+3] = 'bar'
47
48 # Check that the modification worked
49 self.assertEqual(m[0], '3')
50 self.assertEqual(m[0:3], '3\0\0')
51 self.assertEqual(m[PAGESIZE-1 : PAGESIZE + 7], '\0foobar\0')
52
53 m.flush()
54
55 # Test doing a regular expression match in an mmap'ed file
56 match = re.search('[A-Za-z]+', m)
57 if match is None:
58 self.fail('regex match on mmap failed!')
59 else:
60 start, end = match.span(0)
61 length = end - start
62
63 self.assertEqual(start, PAGESIZE)
64 self.assertEqual(end, PAGESIZE + 6)
65
66 # test seeking around (try to overflow the seek implementation)
67 m.seek(0,0)
68 self.assertEqual(m.tell(), 0)
69 m.seek(42,1)
70 self.assertEqual(m.tell(), 42)
71 m.seek(0,2)
72 self.assertEqual(m.tell(), len(m))
73
74 # Try to seek to negative position...
75 self.assertRaises(ValueError, m.seek, -1)
76
77 # Try to seek beyond end of mmap...
78 self.assertRaises(ValueError, m.seek, 1, 2)
79
80 # Try to seek to negative position...
81 self.assertRaises(ValueError, m.seek, -len(m)-1, 2)
82
83 # Try resizing map
84 try:
85 m.resize(512)
86 except SystemError:
87 # resize() not supported
88 # No messages are printed, since the output of this test suite
89 # would then be different across platforms.
90 pass
91 else:
92 # resize() is supported
93 self.assertEqual(len(m), 512)
94 # Check that we can no longer seek beyond the new size.
95 self.assertRaises(ValueError, m.seek, 513, 0)
96
97 # Check that the underlying file is truncated too
98 # (bug #728515)
99 f = open(TESTFN)
100 f.seek(0, 2)
101 self.assertEqual(f.tell(), 512)
102 f.close()
103 self.assertEqual(m.size(), 512)
104
105 m.close()
106
107 finally:
108 try:
109 f.close()
110 except OSError:
111 pass
112
113 def test_access_parameter(self):
114 # Test for "access" keyword parameter
Tim Peters5ebfd362001-11-13 23:11:19 +0000115 mapsize = 10
Tim Peters5ebfd362001-11-13 23:11:19 +0000116 open(TESTFN, "wb").write("a"*mapsize)
Tim Peters5ebfd362001-11-13 23:11:19 +0000117 f = open(TESTFN, "rb")
118 m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
Georg Brandl31631792006-10-29 19:13:40 +0000119 self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.")
Tim Peters5ebfd362001-11-13 23:11:19 +0000120
Georg Brandl31631792006-10-29 19:13:40 +0000121 # Ensuring that readonly mmap can't be slice assigned
Tim Peters5ebfd362001-11-13 23:11:19 +0000122 try:
123 m[:] = 'b'*mapsize
124 except TypeError:
125 pass
126 else:
Georg Brandl31631792006-10-29 19:13:40 +0000127 self.fail("Able to write to readonly memory map")
Tim Peters5ebfd362001-11-13 23:11:19 +0000128
Georg Brandl31631792006-10-29 19:13:40 +0000129 # Ensuring that readonly mmap can't be item assigned
Tim Peters5ebfd362001-11-13 23:11:19 +0000130 try:
131 m[0] = 'b'
132 except TypeError:
133 pass
134 else:
Georg Brandl31631792006-10-29 19:13:40 +0000135 self.fail("Able to write to readonly memory map")
Tim Peters5ebfd362001-11-13 23:11:19 +0000136
Georg Brandl31631792006-10-29 19:13:40 +0000137 # Ensuring that readonly mmap can't be write() to
Tim Peters5ebfd362001-11-13 23:11:19 +0000138 try:
139 m.seek(0,0)
140 m.write('abc')
141 except TypeError:
142 pass
143 else:
Georg Brandl31631792006-10-29 19:13:40 +0000144 self.fail("Able to write to readonly memory map")
Tim Peters5ebfd362001-11-13 23:11:19 +0000145
Georg Brandl31631792006-10-29 19:13:40 +0000146 # Ensuring that readonly mmap can't be write_byte() to
Tim Peters5ebfd362001-11-13 23:11:19 +0000147 try:
148 m.seek(0,0)
149 m.write_byte('d')
150 except TypeError:
151 pass
152 else:
Georg Brandl31631792006-10-29 19:13:40 +0000153 self.fail("Able to write to readonly memory map")
Tim Peters5ebfd362001-11-13 23:11:19 +0000154
Georg Brandl31631792006-10-29 19:13:40 +0000155 # Ensuring that readonly mmap can't be resized
Tim Peters5ebfd362001-11-13 23:11:19 +0000156 try:
157 m.resize(2*mapsize)
158 except SystemError: # resize is not universally supported
159 pass
160 except TypeError:
161 pass
162 else:
Georg Brandl31631792006-10-29 19:13:40 +0000163 self.fail("Able to resize readonly memory map")
Neal Norwitzd48a2f72008-04-01 05:40:43 +0000164 f.close()
Tim Peters5ebfd362001-11-13 23:11:19 +0000165 del m, f
Georg Brandl31631792006-10-29 19:13:40 +0000166 self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize,
Tim Peters5ebfd362001-11-13 23:11:19 +0000167 "Readonly memory map data file was modified")
168
Georg Brandl31631792006-10-29 19:13:40 +0000169 # Opening mmap with size too big
Neal Norwitzb5673922002-09-05 21:48:07 +0000170 import sys
171 f = open(TESTFN, "r+b")
172 try:
173 m = mmap.mmap(f.fileno(), mapsize+1)
174 except ValueError:
175 # we do not expect a ValueError on Windows
Tim Peters4f4f4d72002-09-10 20:49:15 +0000176 # CAUTION: This also changes the size of the file on disk, and
177 # later tests assume that the length hasn't changed. We need to
178 # repair that.
Neal Norwitzb5673922002-09-05 21:48:07 +0000179 if sys.platform.startswith('win'):
Georg Brandl31631792006-10-29 19:13:40 +0000180 self.fail("Opening mmap with size+1 should work on Windows.")
Neal Norwitzb5673922002-09-05 21:48:07 +0000181 else:
182 # we expect a ValueError on Unix, but not on Windows
183 if not sys.platform.startswith('win'):
Georg Brandl31631792006-10-29 19:13:40 +0000184 self.fail("Opening mmap with size+1 should raise ValueError.")
Barry Warsawccd9e752002-09-11 02:56:42 +0000185 m.close()
Tim Peters4f4f4d72002-09-10 20:49:15 +0000186 f.close()
187 if sys.platform.startswith('win'):
188 # Repair damage from the resizing test.
189 f = open(TESTFN, 'r+b')
190 f.truncate(mapsize)
191 f.close()
Neal Norwitzb5673922002-09-05 21:48:07 +0000192
Georg Brandl31631792006-10-29 19:13:40 +0000193 # Opening mmap with access=ACCESS_WRITE
Tim Peters5ebfd362001-11-13 23:11:19 +0000194 f = open(TESTFN, "r+b")
195 m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
Georg Brandl31631792006-10-29 19:13:40 +0000196 # Modifying write-through memory map
Tim Peters5ebfd362001-11-13 23:11:19 +0000197 m[:] = 'c'*mapsize
Georg Brandl31631792006-10-29 19:13:40 +0000198 self.assertEqual(m[:], 'c'*mapsize,
Tim Peters5ebfd362001-11-13 23:11:19 +0000199 "Write-through memory map memory not updated properly.")
200 m.flush()
Tim Peters1b5112a2002-09-10 21:19:55 +0000201 m.close()
202 f.close()
Tim Peters4f4f4d72002-09-10 20:49:15 +0000203 f = open(TESTFN, 'rb')
204 stuff = f.read()
205 f.close()
Georg Brandl31631792006-10-29 19:13:40 +0000206 self.assertEqual(stuff, 'c'*mapsize,
Tim Peters5ebfd362001-11-13 23:11:19 +0000207 "Write-through memory map data file not updated properly.")
208
Georg Brandl31631792006-10-29 19:13:40 +0000209 # Opening mmap with access=ACCESS_COPY
Tim Peters5ebfd362001-11-13 23:11:19 +0000210 f = open(TESTFN, "r+b")
211 m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
Georg Brandl31631792006-10-29 19:13:40 +0000212 # Modifying copy-on-write memory map
Tim Peters5ebfd362001-11-13 23:11:19 +0000213 m[:] = 'd'*mapsize
Georg Brandl31631792006-10-29 19:13:40 +0000214 self.assertEqual(m[:], 'd' * mapsize,
Tim Peters5ebfd362001-11-13 23:11:19 +0000215 "Copy-on-write memory map data not written correctly.")
216 m.flush()
Georg Brandl31631792006-10-29 19:13:40 +0000217 self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize,
Tim Peters5ebfd362001-11-13 23:11:19 +0000218 "Copy-on-write test data file should not be modified.")
Georg Brandl31631792006-10-29 19:13:40 +0000219 # Ensuring copy-on-write maps cannot be resized
220 self.assertRaises(TypeError, m.resize, 2*mapsize)
Neal Norwitzd48a2f72008-04-01 05:40:43 +0000221 f.close()
Tim Peters5ebfd362001-11-13 23:11:19 +0000222 del m, f
Tim Petersabd8a332006-11-03 02:32:46 +0000223
Georg Brandl31631792006-10-29 19:13:40 +0000224 # Ensuring invalid access parameter raises exception
225 f = open(TESTFN, "r+b")
226 self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
227 f.close()
Tim Peters5ebfd362001-11-13 23:11:19 +0000228
229 if os.name == "posix":
Tim Peters00cafa02001-11-13 23:39:47 +0000230 # Try incompatible flags, prot and access parameters.
231 f = open(TESTFN, "r+b")
Georg Brandl31631792006-10-29 19:13:40 +0000232 self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
233 flags=mmap.MAP_PRIVATE,
Tim Peters5ebfd362001-11-13 23:11:19 +0000234 prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
Tim Peters5379dea2002-04-18 04:30:18 +0000235 f.close()
Tim Peters5ebfd362001-11-13 23:11:19 +0000236
Georg Brandl31631792006-10-29 19:13:40 +0000237 def test_bad_file_desc(self):
238 # Try opening a bad file descriptor...
239 self.assertRaises(mmap.error, mmap.mmap, -2, 4096)
Neal Norwitz3b4fff82006-01-11 08:54:45 +0000240
Georg Brandl31631792006-10-29 19:13:40 +0000241 def test_tougher_find(self):
242 # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2,
243 # searching for data with embedded \0 bytes didn't work.
244 f = open(TESTFN, 'w+')
Tim Petersc9ffa062002-03-08 05:43:32 +0000245
Tim Petersc9ffa062002-03-08 05:43:32 +0000246 data = 'aabaac\x00deef\x00\x00aa\x00'
247 n = len(data)
248 f.write(data)
Tim Peters5379dea2002-04-18 04:30:18 +0000249 f.flush()
Tim Petersc9ffa062002-03-08 05:43:32 +0000250 m = mmap.mmap(f.fileno(), n)
251 f.close()
252
253 for start in range(n+1):
254 for finish in range(start, n+1):
255 slice = data[start : finish]
Georg Brandl31631792006-10-29 19:13:40 +0000256 self.assertEqual(m.find(slice), data.find(slice))
257 self.assertEqual(m.find(slice + 'x'), -1)
Tim Petersddc82ea2003-01-13 21:38:45 +0000258 m.close()
Tim Petersc9ffa062002-03-08 05:43:32 +0000259
Andrew M. Kuchling5c60bfc2008-01-19 18:18:41 +0000260 def test_find_end(self):
261 # test the new 'end' parameter works as expected
262 f = open(TESTFN, 'w+')
263 data = 'one two ones'
264 n = len(data)
265 f.write(data)
266 f.flush()
267 m = mmap.mmap(f.fileno(), n)
268 f.close()
269
270 self.assertEqual(m.find('one'), 0)
271 self.assertEqual(m.find('ones'), 8)
272 self.assertEqual(m.find('one', 0, -1), 0)
273 self.assertEqual(m.find('one', 1), 8)
274 self.assertEqual(m.find('one', 1, -1), 8)
275 self.assertEqual(m.find('one', 1, -2), -1)
276
277
278 def test_rfind(self):
279 # test the new 'end' parameter works as expected
280 f = open(TESTFN, 'w+')
281 data = 'one two ones'
282 n = len(data)
283 f.write(data)
284 f.flush()
285 m = mmap.mmap(f.fileno(), n)
286 f.close()
287
288 self.assertEqual(m.rfind('one'), 8)
289 self.assertEqual(m.rfind('one '), 0)
290 self.assertEqual(m.rfind('one', 0, -1), 8)
291 self.assertEqual(m.rfind('one', 0, -2), 0)
292 self.assertEqual(m.rfind('one', 1, -1), 8)
293 self.assertEqual(m.rfind('one', 1, -2), -1)
294
295
Georg Brandl31631792006-10-29 19:13:40 +0000296 def test_double_close(self):
297 # make sure a double close doesn't crash on Solaris (Bug# 665913)
298 f = open(TESTFN, 'w+')
Tim Petersc9ffa062002-03-08 05:43:32 +0000299
Tim Petersddc82ea2003-01-13 21:38:45 +0000300 f.write(2**16 * 'a') # Arbitrary character
Neal Norwitze604c022003-01-10 20:52:16 +0000301 f.close()
302
303 f = open(TESTFN)
Tim Petersddc82ea2003-01-13 21:38:45 +0000304 mf = mmap.mmap(f.fileno(), 2**16, access=mmap.ACCESS_READ)
Neal Norwitze604c022003-01-10 20:52:16 +0000305 mf.close()
306 mf.close()
307 f.close()
308
Georg Brandl31631792006-10-29 19:13:40 +0000309 def test_entire_file(self):
310 # test mapping of entire file by passing 0 for map length
311 if hasattr(os, "stat"):
312 f = open(TESTFN, "w+")
Tim Petersc9ffa062002-03-08 05:43:32 +0000313
Martin v. Löwis7fe60c02005-03-03 11:22:44 +0000314 f.write(2**16 * 'm') # Arbitrary character
315 f.close()
316
317 f = open(TESTFN, "rb+")
Tim Peterseba28be2005-03-28 01:08:02 +0000318 mf = mmap.mmap(f.fileno(), 0)
Georg Brandl31631792006-10-29 19:13:40 +0000319 self.assertEqual(len(mf), 2**16, "Map size should equal file size.")
320 self.assertEqual(mf.read(2**16), 2**16 * "m")
Martin v. Löwis7fe60c02005-03-03 11:22:44 +0000321 mf.close()
322 f.close()
323
Georg Brandl31631792006-10-29 19:13:40 +0000324 def test_move(self):
325 # make move works everywhere (64-bit format problem earlier)
326 f = open(TESTFN, 'w+')
Tim Peterseba28be2005-03-28 01:08:02 +0000327
Neal Norwitz8856fb72005-12-18 03:34:22 +0000328 f.write("ABCDEabcde") # Arbitrary character
329 f.flush()
330
331 mf = mmap.mmap(f.fileno(), 10)
332 mf.move(5, 0, 5)
Georg Brandl31631792006-10-29 19:13:40 +0000333 self.assertEqual(mf[:], "ABCDEABCDE", "Map move should have duplicated front 5")
Neal Norwitz8856fb72005-12-18 03:34:22 +0000334 mf.close()
335 f.close()
336
Georg Brandl31631792006-10-29 19:13:40 +0000337 def test_anonymous(self):
338 # anonymous mmap.mmap(-1, PAGE)
339 m = mmap.mmap(-1, PAGESIZE)
340 for x in xrange(PAGESIZE):
341 self.assertEqual(m[x], '\0', "anonymously mmap'ed contents should be zero")
Neal Norwitz8856fb72005-12-18 03:34:22 +0000342
Georg Brandl31631792006-10-29 19:13:40 +0000343 for x in xrange(PAGESIZE):
344 m[x] = ch = chr(x & 255)
345 self.assertEqual(m[x], ch)
Neal Norwitz0e6bc8c2006-02-05 05:45:43 +0000346
Thomas Wouters3ccec682007-08-28 15:28:19 +0000347 def test_extended_getslice(self):
348 # Test extended slicing by comparing with list slicing.
349 s = "".join(chr(c) for c in reversed(range(256)))
350 m = mmap.mmap(-1, len(s))
351 m[:] = s
352 self.assertEqual(m[:], s)
353 indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
354 for start in indices:
355 for stop in indices:
356 # Skip step 0 (invalid)
357 for step in indices[1:]:
358 self.assertEqual(m[start:stop:step],
359 s[start:stop:step])
360
361 def test_extended_set_del_slice(self):
362 # Test extended slicing by comparing with list slicing.
363 s = "".join(chr(c) for c in reversed(range(256)))
364 m = mmap.mmap(-1, len(s))
365 indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
366 for start in indices:
367 for stop in indices:
368 # Skip invalid step 0
369 for step in indices[1:]:
370 m[:] = s
371 self.assertEqual(m[:], s)
372 L = list(s)
373 # Make sure we have a slice of exactly the right length,
374 # but with different data.
375 data = L[start:stop:step]
376 data = "".join(reversed(data))
377 L[start:stop:step] = data
378 m[start:stop:step] = data
379 self.assertEquals(m[:], "".join(L))
380
Travis E. Oliphant8feafab2007-10-23 02:40:56 +0000381 def make_mmap_file (self, f, halfsize):
382 # Write 2 pages worth of data to the file
383 f.write ('\0' * halfsize)
384 f.write ('foo')
385 f.write ('\0' * (halfsize - 3))
386 f.flush ()
387 return mmap.mmap (f.fileno(), 0)
388
389 def test_offset (self):
390 f = open (TESTFN, 'w+b')
391
392 try: # unlink TESTFN no matter what
393 halfsize = mmap.ALLOCATIONGRANULARITY
394 m = self.make_mmap_file (f, halfsize)
395 m.close ()
396 f.close ()
397
398 mapsize = halfsize * 2
399 # Try invalid offset
400 f = open(TESTFN, "r+b")
401 for offset in [-2, -1, None]:
402 try:
403 m = mmap.mmap(f.fileno(), mapsize, offset=offset)
404 self.assertEqual(0, 1)
405 except (ValueError, TypeError, OverflowError):
406 pass
407 else:
408 self.assertEqual(0, 0)
409 f.close()
410
411 # Try valid offset, hopefully 8192 works on all OSes
412 f = open(TESTFN, "r+b")
413 m = mmap.mmap(f.fileno(), mapsize - halfsize, offset=halfsize)
414 self.assertEqual(m[0:3], 'foo')
415 f.close()
416 m.close()
417
418 finally:
419 f.close()
420 try:
421 os.unlink(TESTFN)
422 except OSError:
423 pass
424
Georg Brandld02fc482008-01-22 19:56:03 +0000425 def test_subclass(self):
426 class anon_mmap(mmap.mmap):
427 def __new__(klass, *args, **kwargs):
428 return mmap.mmap.__new__(klass, -1, *args, **kwargs)
429 anon_mmap(PAGESIZE)
430
Christian Heimes7adfad82008-02-15 08:20:11 +0000431 def test_prot_readonly(self):
Amaury Forgeot d'Arc64d68432008-02-16 00:16:50 +0000432 if not hasattr(mmap, 'PROT_READ'):
433 return
Christian Heimes7adfad82008-02-15 08:20:11 +0000434 mapsize = 10
435 open(TESTFN, "wb").write("a"*mapsize)
436 f = open(TESTFN, "rb")
437 m = mmap.mmap(f.fileno(), mapsize, prot=mmap.PROT_READ)
438 self.assertRaises(TypeError, m.write, "foo")
Neal Norwitzd48a2f72008-04-01 05:40:43 +0000439 f.close()
Georg Brandld02fc482008-01-22 19:56:03 +0000440
Facundo Batistae1396882008-02-17 18:59:29 +0000441 def test_error(self):
442 self.assert_(issubclass(mmap.error, EnvironmentError))
443 self.assert_("mmap.error" in str(mmap.error))
444
445
Georg Brandl31631792006-10-29 19:13:40 +0000446def test_main():
447 run_unittest(MmapTests)
Andrew M. Kuchlinge81b9cf2000-03-30 21:15:29 +0000448
Georg Brandl31631792006-10-29 19:13:40 +0000449if __name__ == '__main__':
450 test_main()