blob: e1e59670c6c9cbee85cc4bb9e8e33c5f6c8c24ff [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
Hirokazu Yamamotof6bbd0e2009-02-17 10:12:10 +000044 # Shouldn't crash on boundary (Issue #5292)
45 self.assertRaises(IndexError, m.__getitem__, len(m))
46 self.assertRaises(IndexError, m.__setitem__, len(m), '\0')
47
Georg Brandl31631792006-10-29 19:13:40 +000048 # Modify the file's content
49 m[0] = '3'
50 m[PAGESIZE +3: PAGESIZE +3+3] = 'bar'
51
52 # Check that the modification worked
53 self.assertEqual(m[0], '3')
54 self.assertEqual(m[0:3], '3\0\0')
55 self.assertEqual(m[PAGESIZE-1 : PAGESIZE + 7], '\0foobar\0')
56
57 m.flush()
58
59 # Test doing a regular expression match in an mmap'ed file
60 match = re.search('[A-Za-z]+', m)
61 if match is None:
62 self.fail('regex match on mmap failed!')
63 else:
64 start, end = match.span(0)
65 length = end - start
66
67 self.assertEqual(start, PAGESIZE)
68 self.assertEqual(end, PAGESIZE + 6)
69
70 # test seeking around (try to overflow the seek implementation)
71 m.seek(0,0)
72 self.assertEqual(m.tell(), 0)
73 m.seek(42,1)
74 self.assertEqual(m.tell(), 42)
75 m.seek(0,2)
76 self.assertEqual(m.tell(), len(m))
77
78 # Try to seek to negative position...
79 self.assertRaises(ValueError, m.seek, -1)
80
81 # Try to seek beyond end of mmap...
82 self.assertRaises(ValueError, m.seek, 1, 2)
83
84 # Try to seek to negative position...
85 self.assertRaises(ValueError, m.seek, -len(m)-1, 2)
86
87 # Try resizing map
88 try:
89 m.resize(512)
90 except SystemError:
91 # resize() not supported
92 # No messages are printed, since the output of this test suite
93 # would then be different across platforms.
94 pass
95 else:
96 # resize() is supported
97 self.assertEqual(len(m), 512)
98 # Check that we can no longer seek beyond the new size.
99 self.assertRaises(ValueError, m.seek, 513, 0)
100
101 # Check that the underlying file is truncated too
102 # (bug #728515)
103 f = open(TESTFN)
104 f.seek(0, 2)
105 self.assertEqual(f.tell(), 512)
106 f.close()
107 self.assertEqual(m.size(), 512)
108
109 m.close()
110
111 finally:
112 try:
113 f.close()
114 except OSError:
115 pass
116
117 def test_access_parameter(self):
118 # Test for "access" keyword parameter
Tim Peters5ebfd362001-11-13 23:11:19 +0000119 mapsize = 10
Tim Peters5ebfd362001-11-13 23:11:19 +0000120 open(TESTFN, "wb").write("a"*mapsize)
Tim Peters5ebfd362001-11-13 23:11:19 +0000121 f = open(TESTFN, "rb")
122 m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ)
Georg Brandl31631792006-10-29 19:13:40 +0000123 self.assertEqual(m[:], 'a'*mapsize, "Readonly memory map data incorrect.")
Tim Peters5ebfd362001-11-13 23:11:19 +0000124
Georg Brandl31631792006-10-29 19:13:40 +0000125 # Ensuring that readonly mmap can't be slice assigned
Tim Peters5ebfd362001-11-13 23:11:19 +0000126 try:
127 m[:] = 'b'*mapsize
128 except TypeError:
129 pass
130 else:
Georg Brandl31631792006-10-29 19:13:40 +0000131 self.fail("Able to write to readonly memory map")
Tim Peters5ebfd362001-11-13 23:11:19 +0000132
Georg Brandl31631792006-10-29 19:13:40 +0000133 # Ensuring that readonly mmap can't be item assigned
Tim Peters5ebfd362001-11-13 23:11:19 +0000134 try:
135 m[0] = 'b'
136 except TypeError:
137 pass
138 else:
Georg Brandl31631792006-10-29 19:13:40 +0000139 self.fail("Able to write to readonly memory map")
Tim Peters5ebfd362001-11-13 23:11:19 +0000140
Georg Brandl31631792006-10-29 19:13:40 +0000141 # Ensuring that readonly mmap can't be write() to
Tim Peters5ebfd362001-11-13 23:11:19 +0000142 try:
143 m.seek(0,0)
144 m.write('abc')
145 except TypeError:
146 pass
147 else:
Georg Brandl31631792006-10-29 19:13:40 +0000148 self.fail("Able to write to readonly memory map")
Tim Peters5ebfd362001-11-13 23:11:19 +0000149
Georg Brandl31631792006-10-29 19:13:40 +0000150 # Ensuring that readonly mmap can't be write_byte() to
Tim Peters5ebfd362001-11-13 23:11:19 +0000151 try:
152 m.seek(0,0)
153 m.write_byte('d')
154 except TypeError:
155 pass
156 else:
Georg Brandl31631792006-10-29 19:13:40 +0000157 self.fail("Able to write to readonly memory map")
Tim Peters5ebfd362001-11-13 23:11:19 +0000158
Georg Brandl31631792006-10-29 19:13:40 +0000159 # Ensuring that readonly mmap can't be resized
Tim Peters5ebfd362001-11-13 23:11:19 +0000160 try:
161 m.resize(2*mapsize)
162 except SystemError: # resize is not universally supported
163 pass
164 except TypeError:
165 pass
166 else:
Georg Brandl31631792006-10-29 19:13:40 +0000167 self.fail("Able to resize readonly memory map")
Neal Norwitzd48a2f72008-04-01 05:40:43 +0000168 f.close()
Tim Peters5ebfd362001-11-13 23:11:19 +0000169 del m, f
Georg Brandl31631792006-10-29 19:13:40 +0000170 self.assertEqual(open(TESTFN, "rb").read(), 'a'*mapsize,
Tim Peters5ebfd362001-11-13 23:11:19 +0000171 "Readonly memory map data file was modified")
172
Georg Brandl31631792006-10-29 19:13:40 +0000173 # Opening mmap with size too big
Neal Norwitzb5673922002-09-05 21:48:07 +0000174 import sys
175 f = open(TESTFN, "r+b")
176 try:
177 m = mmap.mmap(f.fileno(), mapsize+1)
178 except ValueError:
179 # we do not expect a ValueError on Windows
Tim Peters4f4f4d72002-09-10 20:49:15 +0000180 # CAUTION: This also changes the size of the file on disk, and
181 # later tests assume that the length hasn't changed. We need to
182 # repair that.
Neal Norwitzb5673922002-09-05 21:48:07 +0000183 if sys.platform.startswith('win'):
Georg Brandl31631792006-10-29 19:13:40 +0000184 self.fail("Opening mmap with size+1 should work on Windows.")
Neal Norwitzb5673922002-09-05 21:48:07 +0000185 else:
186 # we expect a ValueError on Unix, but not on Windows
187 if not sys.platform.startswith('win'):
Georg Brandl31631792006-10-29 19:13:40 +0000188 self.fail("Opening mmap with size+1 should raise ValueError.")
Barry Warsawccd9e752002-09-11 02:56:42 +0000189 m.close()
Tim Peters4f4f4d72002-09-10 20:49:15 +0000190 f.close()
191 if sys.platform.startswith('win'):
192 # Repair damage from the resizing test.
193 f = open(TESTFN, 'r+b')
194 f.truncate(mapsize)
195 f.close()
Neal Norwitzb5673922002-09-05 21:48:07 +0000196
Georg Brandl31631792006-10-29 19:13:40 +0000197 # Opening mmap with access=ACCESS_WRITE
Tim Peters5ebfd362001-11-13 23:11:19 +0000198 f = open(TESTFN, "r+b")
199 m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE)
Georg Brandl31631792006-10-29 19:13:40 +0000200 # Modifying write-through memory map
Tim Peters5ebfd362001-11-13 23:11:19 +0000201 m[:] = 'c'*mapsize
Georg Brandl31631792006-10-29 19:13:40 +0000202 self.assertEqual(m[:], 'c'*mapsize,
Tim Peters5ebfd362001-11-13 23:11:19 +0000203 "Write-through memory map memory not updated properly.")
204 m.flush()
Tim Peters1b5112a2002-09-10 21:19:55 +0000205 m.close()
206 f.close()
Tim Peters4f4f4d72002-09-10 20:49:15 +0000207 f = open(TESTFN, 'rb')
208 stuff = f.read()
209 f.close()
Georg Brandl31631792006-10-29 19:13:40 +0000210 self.assertEqual(stuff, 'c'*mapsize,
Tim Peters5ebfd362001-11-13 23:11:19 +0000211 "Write-through memory map data file not updated properly.")
212
Georg Brandl31631792006-10-29 19:13:40 +0000213 # Opening mmap with access=ACCESS_COPY
Tim Peters5ebfd362001-11-13 23:11:19 +0000214 f = open(TESTFN, "r+b")
215 m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY)
Georg Brandl31631792006-10-29 19:13:40 +0000216 # Modifying copy-on-write memory map
Tim Peters5ebfd362001-11-13 23:11:19 +0000217 m[:] = 'd'*mapsize
Georg Brandl31631792006-10-29 19:13:40 +0000218 self.assertEqual(m[:], 'd' * mapsize,
Tim Peters5ebfd362001-11-13 23:11:19 +0000219 "Copy-on-write memory map data not written correctly.")
220 m.flush()
Georg Brandl31631792006-10-29 19:13:40 +0000221 self.assertEqual(open(TESTFN, "rb").read(), 'c'*mapsize,
Tim Peters5ebfd362001-11-13 23:11:19 +0000222 "Copy-on-write test data file should not be modified.")
Georg Brandl31631792006-10-29 19:13:40 +0000223 # Ensuring copy-on-write maps cannot be resized
224 self.assertRaises(TypeError, m.resize, 2*mapsize)
Neal Norwitzd48a2f72008-04-01 05:40:43 +0000225 f.close()
Tim Peters5ebfd362001-11-13 23:11:19 +0000226 del m, f
Tim Petersabd8a332006-11-03 02:32:46 +0000227
Georg Brandl31631792006-10-29 19:13:40 +0000228 # Ensuring invalid access parameter raises exception
229 f = open(TESTFN, "r+b")
230 self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize, access=4)
231 f.close()
Tim Peters5ebfd362001-11-13 23:11:19 +0000232
233 if os.name == "posix":
Tim Peters00cafa02001-11-13 23:39:47 +0000234 # Try incompatible flags, prot and access parameters.
235 f = open(TESTFN, "r+b")
Georg Brandl31631792006-10-29 19:13:40 +0000236 self.assertRaises(ValueError, mmap.mmap, f.fileno(), mapsize,
237 flags=mmap.MAP_PRIVATE,
Tim Peters5ebfd362001-11-13 23:11:19 +0000238 prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE)
Tim Peters5379dea2002-04-18 04:30:18 +0000239 f.close()
Tim Peters5ebfd362001-11-13 23:11:19 +0000240
Georg Brandl31631792006-10-29 19:13:40 +0000241 def test_bad_file_desc(self):
242 # Try opening a bad file descriptor...
243 self.assertRaises(mmap.error, mmap.mmap, -2, 4096)
Neal Norwitz3b4fff82006-01-11 08:54:45 +0000244
Georg Brandl31631792006-10-29 19:13:40 +0000245 def test_tougher_find(self):
246 # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2,
247 # searching for data with embedded \0 bytes didn't work.
248 f = open(TESTFN, 'w+')
Tim Petersc9ffa062002-03-08 05:43:32 +0000249
Tim Petersc9ffa062002-03-08 05:43:32 +0000250 data = 'aabaac\x00deef\x00\x00aa\x00'
251 n = len(data)
252 f.write(data)
Tim Peters5379dea2002-04-18 04:30:18 +0000253 f.flush()
Tim Petersc9ffa062002-03-08 05:43:32 +0000254 m = mmap.mmap(f.fileno(), n)
255 f.close()
256
257 for start in range(n+1):
258 for finish in range(start, n+1):
259 slice = data[start : finish]
Georg Brandl31631792006-10-29 19:13:40 +0000260 self.assertEqual(m.find(slice), data.find(slice))
261 self.assertEqual(m.find(slice + 'x'), -1)
Tim Petersddc82ea2003-01-13 21:38:45 +0000262 m.close()
Tim Petersc9ffa062002-03-08 05:43:32 +0000263
Andrew M. Kuchling5c60bfc2008-01-19 18:18:41 +0000264 def test_find_end(self):
265 # test the new 'end' parameter works as expected
266 f = open(TESTFN, 'w+')
267 data = 'one two ones'
268 n = len(data)
269 f.write(data)
270 f.flush()
271 m = mmap.mmap(f.fileno(), n)
272 f.close()
273
274 self.assertEqual(m.find('one'), 0)
275 self.assertEqual(m.find('ones'), 8)
276 self.assertEqual(m.find('one', 0, -1), 0)
277 self.assertEqual(m.find('one', 1), 8)
278 self.assertEqual(m.find('one', 1, -1), 8)
279 self.assertEqual(m.find('one', 1, -2), -1)
280
281
282 def test_rfind(self):
283 # test the new 'end' parameter works as expected
284 f = open(TESTFN, 'w+')
285 data = 'one two ones'
286 n = len(data)
287 f.write(data)
288 f.flush()
289 m = mmap.mmap(f.fileno(), n)
290 f.close()
291
292 self.assertEqual(m.rfind('one'), 8)
293 self.assertEqual(m.rfind('one '), 0)
294 self.assertEqual(m.rfind('one', 0, -1), 8)
295 self.assertEqual(m.rfind('one', 0, -2), 0)
296 self.assertEqual(m.rfind('one', 1, -1), 8)
297 self.assertEqual(m.rfind('one', 1, -2), -1)
298
299
Georg Brandl31631792006-10-29 19:13:40 +0000300 def test_double_close(self):
301 # make sure a double close doesn't crash on Solaris (Bug# 665913)
302 f = open(TESTFN, 'w+')
Tim Petersc9ffa062002-03-08 05:43:32 +0000303
Tim Petersddc82ea2003-01-13 21:38:45 +0000304 f.write(2**16 * 'a') # Arbitrary character
Neal Norwitze604c022003-01-10 20:52:16 +0000305 f.close()
306
307 f = open(TESTFN)
Tim Petersddc82ea2003-01-13 21:38:45 +0000308 mf = mmap.mmap(f.fileno(), 2**16, access=mmap.ACCESS_READ)
Neal Norwitze604c022003-01-10 20:52:16 +0000309 mf.close()
310 mf.close()
311 f.close()
312
Georg Brandl31631792006-10-29 19:13:40 +0000313 def test_entire_file(self):
314 # test mapping of entire file by passing 0 for map length
315 if hasattr(os, "stat"):
316 f = open(TESTFN, "w+")
Tim Petersc9ffa062002-03-08 05:43:32 +0000317
Martin v. Löwis7fe60c02005-03-03 11:22:44 +0000318 f.write(2**16 * 'm') # Arbitrary character
319 f.close()
320
321 f = open(TESTFN, "rb+")
Tim Peterseba28be2005-03-28 01:08:02 +0000322 mf = mmap.mmap(f.fileno(), 0)
Georg Brandl31631792006-10-29 19:13:40 +0000323 self.assertEqual(len(mf), 2**16, "Map size should equal file size.")
324 self.assertEqual(mf.read(2**16), 2**16 * "m")
Martin v. Löwis7fe60c02005-03-03 11:22:44 +0000325 mf.close()
326 f.close()
327
Georg Brandl31631792006-10-29 19:13:40 +0000328 def test_move(self):
329 # make move works everywhere (64-bit format problem earlier)
330 f = open(TESTFN, 'w+')
Tim Peterseba28be2005-03-28 01:08:02 +0000331
Neal Norwitz8856fb72005-12-18 03:34:22 +0000332 f.write("ABCDEabcde") # Arbitrary character
333 f.flush()
334
335 mf = mmap.mmap(f.fileno(), 10)
336 mf.move(5, 0, 5)
Georg Brandl31631792006-10-29 19:13:40 +0000337 self.assertEqual(mf[:], "ABCDEABCDE", "Map move should have duplicated front 5")
Neal Norwitz8856fb72005-12-18 03:34:22 +0000338 mf.close()
339 f.close()
340
Georg Brandl31631792006-10-29 19:13:40 +0000341 def test_anonymous(self):
342 # anonymous mmap.mmap(-1, PAGE)
343 m = mmap.mmap(-1, PAGESIZE)
344 for x in xrange(PAGESIZE):
345 self.assertEqual(m[x], '\0', "anonymously mmap'ed contents should be zero")
Neal Norwitz8856fb72005-12-18 03:34:22 +0000346
Georg Brandl31631792006-10-29 19:13:40 +0000347 for x in xrange(PAGESIZE):
348 m[x] = ch = chr(x & 255)
349 self.assertEqual(m[x], ch)
Neal Norwitz0e6bc8c2006-02-05 05:45:43 +0000350
Thomas Wouters3ccec682007-08-28 15:28:19 +0000351 def test_extended_getslice(self):
352 # Test extended slicing by comparing with list slicing.
353 s = "".join(chr(c) for c in reversed(range(256)))
354 m = mmap.mmap(-1, len(s))
355 m[:] = s
356 self.assertEqual(m[:], s)
357 indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
358 for start in indices:
359 for stop in indices:
360 # Skip step 0 (invalid)
361 for step in indices[1:]:
362 self.assertEqual(m[start:stop:step],
363 s[start:stop:step])
364
365 def test_extended_set_del_slice(self):
366 # Test extended slicing by comparing with list slicing.
367 s = "".join(chr(c) for c in reversed(range(256)))
368 m = mmap.mmap(-1, len(s))
369 indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300)
370 for start in indices:
371 for stop in indices:
372 # Skip invalid step 0
373 for step in indices[1:]:
374 m[:] = s
375 self.assertEqual(m[:], s)
376 L = list(s)
377 # Make sure we have a slice of exactly the right length,
378 # but with different data.
379 data = L[start:stop:step]
380 data = "".join(reversed(data))
381 L[start:stop:step] = data
382 m[start:stop:step] = data
383 self.assertEquals(m[:], "".join(L))
384
Travis E. Oliphant8feafab2007-10-23 02:40:56 +0000385 def make_mmap_file (self, f, halfsize):
386 # Write 2 pages worth of data to the file
387 f.write ('\0' * halfsize)
388 f.write ('foo')
389 f.write ('\0' * (halfsize - 3))
390 f.flush ()
391 return mmap.mmap (f.fileno(), 0)
392
393 def test_offset (self):
394 f = open (TESTFN, 'w+b')
395
396 try: # unlink TESTFN no matter what
397 halfsize = mmap.ALLOCATIONGRANULARITY
398 m = self.make_mmap_file (f, halfsize)
399 m.close ()
400 f.close ()
401
402 mapsize = halfsize * 2
403 # Try invalid offset
404 f = open(TESTFN, "r+b")
405 for offset in [-2, -1, None]:
406 try:
407 m = mmap.mmap(f.fileno(), mapsize, offset=offset)
408 self.assertEqual(0, 1)
409 except (ValueError, TypeError, OverflowError):
410 pass
411 else:
412 self.assertEqual(0, 0)
413 f.close()
414
415 # Try valid offset, hopefully 8192 works on all OSes
416 f = open(TESTFN, "r+b")
417 m = mmap.mmap(f.fileno(), mapsize - halfsize, offset=halfsize)
418 self.assertEqual(m[0:3], 'foo')
419 f.close()
420 m.close()
421
422 finally:
423 f.close()
424 try:
425 os.unlink(TESTFN)
426 except OSError:
427 pass
428
Georg Brandld02fc482008-01-22 19:56:03 +0000429 def test_subclass(self):
430 class anon_mmap(mmap.mmap):
431 def __new__(klass, *args, **kwargs):
432 return mmap.mmap.__new__(klass, -1, *args, **kwargs)
433 anon_mmap(PAGESIZE)
434
Christian Heimes7adfad82008-02-15 08:20:11 +0000435 def test_prot_readonly(self):
Amaury Forgeot d'Arc64d68432008-02-16 00:16:50 +0000436 if not hasattr(mmap, 'PROT_READ'):
437 return
Christian Heimes7adfad82008-02-15 08:20:11 +0000438 mapsize = 10
439 open(TESTFN, "wb").write("a"*mapsize)
440 f = open(TESTFN, "rb")
441 m = mmap.mmap(f.fileno(), mapsize, prot=mmap.PROT_READ)
442 self.assertRaises(TypeError, m.write, "foo")
Neal Norwitzd48a2f72008-04-01 05:40:43 +0000443 f.close()
Georg Brandld02fc482008-01-22 19:56:03 +0000444
Facundo Batistae1396882008-02-17 18:59:29 +0000445 def test_error(self):
446 self.assert_(issubclass(mmap.error, EnvironmentError))
447 self.assert_("mmap.error" in str(mmap.error))
448
449
Georg Brandl31631792006-10-29 19:13:40 +0000450def test_main():
451 run_unittest(MmapTests)
Andrew M. Kuchlinge81b9cf2000-03-30 21:15:29 +0000452
Georg Brandl31631792006-10-29 19:13:40 +0000453if __name__ == '__main__':
454 test_main()