blob: b8ecbe7a7fcd29d05dc642fbd0041cb2c969d863 [file] [log] [blame]
Andrew M. Kuchlinge81b9cf2000-03-30 21:15:29 +00001
2import mmap
3import string, os, re, sys
4
5PAGESIZE = mmap.PAGESIZE
6
Guido van Rossum767e7752000-03-31 01:09:14 +00007def test_both():
8 "Test mmap module on Unix systems and Windows"
9
Andrew M. Kuchlinge81b9cf2000-03-30 21:15:29 +000010 # Create an mmap'ed file
11 f = open('foo', 'w+')
12
13 # Write 2 pages worth of data to the file
14 f.write('\0'* PAGESIZE)
15 f.write('foo')
16 f.write('\0'* (PAGESIZE-3) )
Guido van Rossum767e7752000-03-31 01:09:14 +000017
18 if sys.platform[:3]=="win":
19 m = mmap.mmap(f.fileno(), 2 * PAGESIZE)
20 else:
21 m = mmap.mmap(f.fileno(), 2 * PAGESIZE)
Andrew M. Kuchlinge81b9cf2000-03-30 21:15:29 +000022 f.close()
23
24 # Simple sanity checks
25 print ' Position of foo:', string.find(m, 'foo') / float(PAGESIZE), 'pages'
26 assert string.find(m, 'foo') == PAGESIZE
27
28 print ' Length of file:', len(m) / float(PAGESIZE), 'pages'
29 assert len(m) == 2*PAGESIZE
30
31 print ' Contents of byte 0:', repr(m[0])
32 assert m[0] == '\0'
33 print ' Contents of first 3 bytes:', repr(m[0:3])
34 assert m[0:3] == '\0\0\0'
35
36 # Modify the file's content
37 print "\n Modifying file's content..."
38 m[0] = '3'
39 m[PAGESIZE +3: PAGESIZE +3+3]='bar'
40
41 # Check that the modification worked
42 print ' Contents of byte 0:', repr(m[0])
43 assert m[0] == '3'
44 print ' Contents of first 3 bytes:', repr(m[0:3])
45 assert m[0:3] == '3\0\0'
46 print ' Contents of second page:', m[PAGESIZE-1 : PAGESIZE + 7]
47 assert m[PAGESIZE-1 : PAGESIZE + 7] == '\0foobar\0'
48
49 m.flush()
50
51 # Test doing a regular expression match in an mmap'ed file
52 match=re.search('[A-Za-z]+', m)
53 if match == None:
54 print ' ERROR: regex match on mmap failed!'
55 else:
56 start, end = match.span(0)
57 length = end - start
58
59 print ' Regex match on mmap (page start, length of match):',
60 print start / float(PAGESIZE), length
61
62 assert start == PAGESIZE
63 assert end == PAGESIZE + 6
64
65 print ' Test passed'
66
Guido van Rossum767e7752000-03-31 01:09:14 +000067test_both()
68