blob: e5da187e0c73c65b7bf30947962360985f59e56d [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
Guido van Rossum706dbd02000-03-31 01:20:33 +000018 m = mmap.mmap(f.fileno(), 2 * PAGESIZE)
Andrew M. Kuchlinge81b9cf2000-03-30 21:15:29 +000019 f.close()
20
21 # Simple sanity checks
22 print ' Position of foo:', string.find(m, 'foo') / float(PAGESIZE), 'pages'
23 assert string.find(m, 'foo') == PAGESIZE
24
25 print ' Length of file:', len(m) / float(PAGESIZE), 'pages'
26 assert len(m) == 2*PAGESIZE
27
28 print ' Contents of byte 0:', repr(m[0])
29 assert m[0] == '\0'
30 print ' Contents of first 3 bytes:', repr(m[0:3])
31 assert m[0:3] == '\0\0\0'
32
33 # Modify the file's content
34 print "\n Modifying file's content..."
35 m[0] = '3'
36 m[PAGESIZE +3: PAGESIZE +3+3]='bar'
37
38 # Check that the modification worked
39 print ' Contents of byte 0:', repr(m[0])
40 assert m[0] == '3'
41 print ' Contents of first 3 bytes:', repr(m[0:3])
42 assert m[0:3] == '3\0\0'
43 print ' Contents of second page:', m[PAGESIZE-1 : PAGESIZE + 7]
44 assert m[PAGESIZE-1 : PAGESIZE + 7] == '\0foobar\0'
45
46 m.flush()
47
48 # Test doing a regular expression match in an mmap'ed file
49 match=re.search('[A-Za-z]+', m)
50 if match == None:
51 print ' ERROR: regex match on mmap failed!'
52 else:
53 start, end = match.span(0)
54 length = end - start
55
56 print ' Regex match on mmap (page start, length of match):',
57 print start / float(PAGESIZE), length
58
59 assert start == PAGESIZE
60 assert end == PAGESIZE + 6
61
Fred Drake605843f2000-04-05 14:17:11 +000062 m.close()
63 os.unlink("foo")
Andrew M. Kuchlinge81b9cf2000-03-30 21:15:29 +000064 print ' Test passed'
65
Guido van Rossum767e7752000-03-31 01:09:14 +000066test_both()
67