def test_2(): d = globals().copy() def testfunc(): global x x = 1 d['testfunc'] = testfunc profile.runctx("testfunc()", d, d, TESTFN) vereq (x, 1) os.unlink (TESTFN)
def test_anon(): print " anonymous mmap.mmap(-1, PAGESIZE)..." m = mmap.mmap(-1, PAGESIZE) for x in xrange(PAGESIZE): verify(m[x] == '\0', "anonymously mmap'ed contents should be zero") for x in xrange(PAGESIZE): m[x] = ch = chr(x & 255) vereq(m[x], ch)
def test_2(): d = globals().copy() def testfunc(): global x x = 1 d['testfunc'] = testfunc profile.runctx("testfunc()", d, d, TESTFN) vereq(x, 1) os.unlink(TESTFN)
def test_3(): result = [] def testfunc1(): try: len(None) except: pass try: len(None) except: pass result.append(True) def testfunc2(): testfunc1() testfunc1() profile.runctx("testfunc2()", locals(), locals(), TESTFN) vereq(result, [True, True]) os.unlink(TESTFN)
def test_pack_into_fn(): test_string = 'Reykjavik rocks, eow!' writable_buf = array.array('c', ' ' * 100) fmt = '21s' pack_into = lambda *args: struct.pack_into(fmt, *args) # Test without offset. pack_into(writable_buf, 0, test_string) from_buf = writable_buf.tostring()[:len(test_string)] vereq(from_buf, test_string) # Test with offset. pack_into(writable_buf, 10, test_string) from_buf = writable_buf.tostring()[:len(test_string) + 10] vereq(from_buf, test_string[:10] + test_string) # Go beyond boundaries. small_buf = array.array('c', ' ' * 10) assertRaises(struct.error, pack_into, small_buf, 0, test_string) assertRaises(struct.error, pack_into, small_buf, 2, test_string)
def test_pack_into(): test_string = 'Reykjavik rocks, eow!' writable_buf = array.array('c', ' '*100) fmt = '21s' s = struct.Struct(fmt) # Test without offset s.pack_into(writable_buf, 0, test_string) from_buf = writable_buf.tostring()[:len(test_string)] vereq(from_buf, test_string) # Test with offset. s.pack_into(writable_buf, 10, test_string) from_buf = writable_buf.tostring()[:len(test_string)+10] vereq(from_buf, test_string[:10] + test_string) # Go beyond boundaries. small_buf = array.array('c', ' '*10) assertRaises(struct.error, s.pack_into, small_buf, 0, test_string) assertRaises(struct.error, s.pack_into, small_buf, 2, test_string)
def test_pack_into_fn(): test_string = 'Reykjavik rocks, eow!' writable_buf = array.array('c', ' '*100) fmt = '21s' pack_into = lambda *args: struct.pack_into(fmt, *args) # Test without offset. pack_into(writable_buf, 0, test_string) from_buf = writable_buf.tostring()[:len(test_string)] vereq(from_buf, test_string) # Test with offset. pack_into(writable_buf, 10, test_string) from_buf = writable_buf.tostring()[:len(test_string)+10] vereq(from_buf, test_string[:10] + test_string) # Go beyond boundaries. small_buf = array.array('c', ' '*10) assertRaises((struct.error, ValueError), pack_into, small_buf, 0, test_string) assertRaises((struct.error, ValueError), pack_into, small_buf, 2, test_string)
def test_pack_into(): test_string = 'Reykjavik rocks, eow!' writable_buf = array.array('c', ' ' * 100) fmt = '21s' s = struct.Struct(fmt) # Test without offset s.pack_into(writable_buf, 0, test_string) from_buf = writable_buf.tostring()[:len(test_string)] vereq(from_buf, test_string) # Test with offset. s.pack_into(writable_buf, 10, test_string) from_buf = writable_buf.tostring()[:len(test_string) + 10] vereq(from_buf, test_string[:10] + test_string) # Go beyond boundaries. small_buf = array.array('c', ' ' * 10) assertRaises((struct.error, ValueError), s.pack_into, small_buf, 0, test_string) assertRaises((struct.error, ValueError), s.pack_into, small_buf, 2, test_string)
def test_saveall(): # Verify that cyclic garbage like lists show up in gc.garbage if the # SAVEALL option is enabled. # First make sure we don't save away other stuff that just happens to # be waiting for collection. gc.collect() vereq(gc.garbage, []) # if this fails, someone else created immortal trash L = [] L.append(L) id_L = id(L) debug = gc.get_debug() gc.set_debug(debug | gc.DEBUG_SAVEALL) del L gc.collect() gc.set_debug(debug) vereq(len(gc.garbage), 1) obj = gc.garbage.pop() vereq(id(obj), id_L)
pass def f3(two, arguments): pass def f4(two, (compound, (argument, list))): pass def f5((compound, first), two): pass vereq(f2.func_code.co_varnames, ("one_argument",)) vereq(f3.func_code.co_varnames, ("two", "arguments")) if check_impl_detail(jython=True): vereq(f4.func_code.co_varnames, ("two", "(compound, (argument, list))", "compound", "argument", "list")) vereq(f5.func_code.co_varnames, ("(compound, first)", "two", "compound", "first")) elif check_impl_detail(pypy=True): vereq(f4.func_code.co_varnames, ("two", ".2", "compound", "argument", "list")) vereq(f5.func_code.co_varnames, (".0", "two", "compound", "first")) elif check_impl_detail(cpython=True): vereq(f4.func_code.co_varnames, ("two", ".1", "compound", "argument", "list")) vereq(f5.func_code.co_varnames, (".0", "two", "compound", "first")) def a1(one_arg,): pass
from test import test_support import StringIO # SF bug 480215: softspace confused in nested print f = StringIO.StringIO() class C: def __str__(self): print >> f, 'a' return 'b' print >> f, C(), 'c ', 'd\t', 'e' print >> f, 'f', 'g' # In 2.2 & earlier, this printed ' a\nbc d\te\nf g\n' test_support.vereq(f.getvalue(), 'a\nb c d\te\nf g\n')
def test_issue4228(): # Packing a long may yield either 32 or 64 bits x = struct.pack('L', -1)[:4] vereq(x, '\xff' * 4)
def test_unpack_with_buffer(): # SF bug 1563759: struct.unpack doens't support buffer protocol objects data = array.array('B', '\x12\x34\x56\x78') value, = struct.unpack('>I', data) vereq(value, 0x12345678)
def test_unpack_from(): test_string = 'abcd01234' fmt = '4s' s = struct.Struct(fmt) for cls in (str, buffer): data = cls(test_string) vereq(s.unpack_from(data), ('abcd',)) vereq(s.unpack_from(data, 2), ('cd01',)) vereq(s.unpack_from(data, 4), ('0123',)) for i in xrange(6): vereq(s.unpack_from(data, i), (data[i:i+4],)) for i in xrange(6, len(test_string) + 1): simple_err(s.unpack_from, data, i) for cls in (str, buffer): data = cls(test_string) vereq(struct.unpack_from(fmt, data), ('abcd',)) vereq(struct.unpack_from(fmt, data, 2), ('cd01',)) vereq(struct.unpack_from(fmt, data, 4), ('0123',)) for i in xrange(6): vereq(struct.unpack_from(fmt, data, i), (data[i:i+4],)) for i in xrange(6, len(test_string) + 1): simple_err(struct.unpack_from, fmt, data, i)
from test.test_support import vereq, TestFailed import _symtable symbols = _symtable.symtable("def f(x): return x", "?", "exec") vereq(symbols[0].name, "global") vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) # Bug tickler: SyntaxError file name correct whether error raised # while parsing or building symbol table. def checkfilename(brokencode): try: _symtable.symtable(brokencode, "spam", "exec") except SyntaxError, e: vereq(e.filename, "spam") else: raise TestFailed("no SyntaxError for %r" % (brokencode,)) checkfilename("def f(x): foo)(") # parse-time checkfilename("def f(x): global x") # symtable-build-time
def checkfilename(brokencode): try: _symtable.symtable(brokencode, "spam", "exec") except SyntaxError, e: vereq(e.filename, "spam")
warnings.filterwarnings("ignore", r"import \*", SyntaxWarning, "<string>") print "1. simple nesting" def make_adder(x): def adder(y): return x + y return adder inc = make_adder(1) plus10 = make_adder(10) vereq(inc(1), 2) vereq(plus10(-2), 8) print "2. extra nesting" def make_adder2(x): def extra(): # check freevars passing through non-use scopes def adder(y): return x + y return adder return extra()
os.kill(pid, getattr(signal, signame)) print >> sys.__stdout__, " child sent", signame, "to", pid time.sleep(1) finally: os._exit(0) # Install handlers. hup = signal.signal(signal.SIGHUP, handlerA) usr1 = signal.signal(signal.SIGUSR1, handlerB) usr2 = signal.signal(signal.SIGUSR2, signal.SIG_IGN) alrm = signal.signal(signal.SIGALRM, signal.default_int_handler) try: signal.alarm(MAX_DURATION) vereq(signal.getsignal(signal.SIGHUP), handlerA) vereq(signal.getsignal(signal.SIGUSR1), handlerB) vereq(signal.getsignal(signal.SIGUSR2), signal.SIG_IGN) vereq(signal.getsignal(signal.SIGALRM), signal.default_int_handler) # Try to ensure this test exits even if there is some problem with alarm. # Tru64/Alpha often hangs and is ultimately killed by the buildbot. fork_pid = force_test_exit() try: signal.getsignal(4242) raise TestFailed('expected ValueError for invalid signal # to ' 'getsignal()') except ValueError: pass
# tests for slice objects; in particular the indices method. from test.test_support import vereq import sys vereq(slice(None ).indices(10), (0, 10, 1)) vereq(slice(None, None, 2).indices(10), (0, 10, 2)) vereq(slice(1, None, 2).indices(10), (1, 10, 2)) vereq(slice(None, None, -1).indices(10), (9, -1, -1)) vereq(slice(None, None, -2).indices(10), (9, -1, -2)) vereq(slice(3, None, -2).indices(10), (3, -1, -2)) vereq(slice(-100, 100 ).indices(10), slice(None).indices(10)) vereq(slice(100, -100, -1).indices(10), slice(None, None, -1).indices(10)) vereq(slice(-100L, 100L, 2L).indices(10), (0, 10, 2)) vereq(range(10)[::sys.maxint - 1], [0])
def test_issue4228(): # Packing a long may yield either 32 or 64 bits x = struct.pack('L', -1)[:4] vereq(x, '\xff'*4)
def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # 4) Test heapify. for size in range(30): heap = [random.random() for dummy in range(size)] heapify(heap) check_invariant(heap) # 5) Less-naive "N-best" algorithm, much faster (if len(data) is big # enough <wink>) than sorting all of data. However, if we had a max # heap instead of a min heap, it could go faster still via # heapify'ing all of data (linear time), then doing 10 heappops # (10 log-time steps). heap = data[:10] heapify(heap) for item in data[10:]: if item > heap[0]: # this gets rarer the longer we run heapreplace(heap, item) vereq(list(heapiter(heap)), data_sorted[-10:]) # 6) Exercise everything with repeated heapsort checks for trial in xrange(100): size = random.randrange(50) data = [random.randrange(25) for i in range(size)] if trial & 1: # Half of the time, use heapify heap = data[:] heapify(heap) else: # The rest of the time, use heappush heap = [] for item in data: heappush(heap, item) data.sort() sorted = [heappop(heap) for i in range(size)] vereq(data, sorted) # Make user happy if verbose: print "All OK"
### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME] ### | ('**'|'*' '*') NAME) ### | fpdef ['=' test] (',' fpdef ['=' test])* [','] ### fpdef: NAME | '(' fplist ')' ### fplist: fpdef (',' fpdef)* [','] ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test) ### argument: [test '='] test # Really [keyword '='] test def f1(): pass f1() f1(*()) f1(*(), **{}) def f2(one_argument): pass def f3(two, arguments): pass def f4(two, (compound, (argument, list))): pass def f5((compound, first), two): pass vereq(f2.func_code.co_varnames, ('one_argument',)) vereq(f3.func_code.co_varnames, ('two', 'arguments')) if sys.platform.startswith('java'): vereq(f4.func_code.co_varnames, ('two', '(compound, (argument, list))', 'compound', 'argument', 'list',)) vereq(f5.func_code.co_varnames, ('(compound, first)', 'two', 'compound', 'first')) else: vereq(f4.func_code.co_varnames, ('two', '.1', 'compound', 'argument', 'list')) vereq(f5.func_code.co_varnames, ('.0', 'two', 'compound', 'first')) def a1(one_arg,): pass def a2(two, args,): pass def v0(*rest): pass
atexit.register(handler1) atexit.register(handler2) atexit.register(handler2, 7, kw="abc") """ fname = TESTFN + ".py" f = file(fname, "w") f.write(input) f.close() p = popen('"%s" %s' % (executable, fname)) output = p.read() p.close() vereq(output, """\ handler2 (7,) {'kw': 'abc'} handler2 () {} handler1 """) input = """\ def direct(): print "direct exit" import sys sys.exitfunc = direct # Make sure atexit doesn't drop def indirect(): print "indirect exit" import atexit
from test.test_support import vereq, TestFailed import _symtable symbols = _symtable.symtable("def f(x): return x", "?", "exec") vereq(symbols[0].name, "global") vereq(len([ste for ste in symbols.values() if ste.name == "f"]), 1) # Bug tickler: SyntaxError file name correct whether error raised # while parsing or building symbol table. def checkfilename(brokencode): try: _symtable.symtable(brokencode, "spam", "exec") except SyntaxError, e: vereq(e.filename, "spam") else: raise TestFailed("no SyntaxError for %r" % (brokencode, )) checkfilename("def f(x): foo)(") # parse-time checkfilename("def f(x): global x") # symtable-build-time
def check_conversion(num): mpz_num = mpz.mpz(num) vereq(int(mpz_num), num) vereq(long(mpz_num), num) vereq(str(mpz_num), 'mpz(%s)' % ` int(num) `)
def test_both(): "Test mmap module on Unix systems and Windows" # Create a file to be mmap'ed. if os.path.exists(TESTFN): os.unlink(TESTFN) f = open(TESTFN, "w+") try: # unlink TESTFN no matter what # Write 2 pages worth of data to the file f.write("\0" * PAGESIZE) f.write("foo") f.write("\0" * (PAGESIZE - 3)) f.flush() m = mmap.mmap(f.fileno(), 2 * PAGESIZE) f.close() # Simple sanity checks print type(m) # SF bug 128713: segfaulted on Linux print " Position of foo:", m.find("foo") / float(PAGESIZE), "pages" vereq(m.find("foo"), PAGESIZE) print " Length of file:", len(m) / float(PAGESIZE), "pages" vereq(len(m), 2 * PAGESIZE) print " Contents of byte 0:", repr(m[0]) vereq(m[0], "\0") print " Contents of first 3 bytes:", repr(m[0:3]) vereq(m[0:3], "\0\0\0") # Modify the file's content print "\n Modifying file's content..." m[0] = "3" m[PAGESIZE + 3 : PAGESIZE + 3 + 3] = "bar" # Check that the modification worked print " Contents of byte 0:", repr(m[0]) vereq(m[0], "3") print " Contents of first 3 bytes:", repr(m[0:3]) vereq(m[0:3], "3\0\0") print " Contents of second page:", repr(m[PAGESIZE - 1 : PAGESIZE + 7]) vereq(m[PAGESIZE - 1 : PAGESIZE + 7], "\0foobar\0") m.flush() # Test doing a regular expression match in an mmap'ed file match = re.search("[A-Za-z]+", m) if match is None: print " ERROR: regex match on mmap failed!" else: start, end = match.span(0) length = end - start print " Regex match on mmap (page start, length of match):", print start / float(PAGESIZE), length vereq(start, PAGESIZE) vereq(end, PAGESIZE + 6) # test seeking around (try to overflow the seek implementation) m.seek(0, 0) print " Seek to zeroth byte" vereq(m.tell(), 0) m.seek(42, 1) print " Seek to 42nd byte" vereq(m.tell(), 42) m.seek(0, 2) print " Seek to last byte" vereq(m.tell(), len(m)) print " Try to seek to negative position..." try: m.seek(-1) except ValueError: pass else: verify(0, "expected a ValueError but did not get it") print " Try to seek beyond end of mmap..." try: m.seek(1, 2) except ValueError: pass else: verify(0, "expected a ValueError but did not get it") print " Try to seek to negative position..." try: m.seek(-len(m) - 1, 2) except ValueError: pass else: verify(0, "expected a ValueError but did not get it") # Try resizing map print " Attempting resize()" try: m.resize(512) except SystemError: # resize() not supported # No messages are printed, since the output of this test suite # would then be different across platforms. pass else: # resize() is supported verify(len(m) == 512, "len(m) is %d, but expecting 512" % (len(m),)) # Check that we can no longer seek beyond the new size. try: m.seek(513, 0) except ValueError: pass else: verify(0, "Could seek beyond the new size") m.close() finally: try: f.close() except OSError: pass try: os.unlink(TESTFN) except OSError: pass # Test for "access" keyword parameter try: mapsize = 10 print " Creating", mapsize, "byte test data file." open(TESTFN, "wb").write("a" * mapsize) print " Opening mmap with access=ACCESS_READ" f = open(TESTFN, "rb") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ) verify(m[:] == "a" * mapsize, "Readonly memory map data incorrect.") print " Ensuring that readonly mmap can't be slice assigned." try: m[:] = "b" * mapsize except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be item assigned." try: m[0] = "b" except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be write() to." try: m.seek(0, 0) m.write("abc") except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be write_byte() to." try: m.seek(0, 0) m.write_byte("d") except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be resized." try: m.resize(2 * mapsize) except SystemError: # resize is not universally supported pass except TypeError: pass else: verify(0, "Able to resize readonly memory map") del m, f verify(open(TESTFN, "rb").read() == "a" * mapsize, "Readonly memory map data file was modified") print " Opening mmap with size too big" import sys f = open(TESTFN, "r+b") try: m = mmap.mmap(f.fileno(), mapsize + 1) except ValueError: # we do not expect a ValueError on Windows # CAUTION: This also changes the size of the file on disk, and # later tests assume that the length hasn't changed. We need to # repair that. if sys.platform.startswith("win"): verify(0, "Opening mmap with size+1 should work on Windows.") else: # we expect a ValueError on Unix, but not on Windows if not sys.platform.startswith("win"): verify(0, "Opening mmap with size+1 should raise ValueError.") m.close() f.close() if sys.platform.startswith("win"): # Repair damage from the resizing test. f = open(TESTFN, "r+b") f.truncate(mapsize) f.close() print " Opening mmap with access=ACCESS_WRITE" f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE) print " Modifying write-through memory map." m[:] = "c" * mapsize verify(m[:] == "c" * mapsize, "Write-through memory map memory not updated properly.") m.flush() m.close() f.close() f = open(TESTFN, "rb") stuff = f.read() f.close() verify(stuff == "c" * mapsize, "Write-through memory map data file not updated properly.") print " Opening mmap with access=ACCESS_COPY" f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY) print " Modifying copy-on-write memory map." m[:] = "d" * mapsize verify(m[:] == "d" * mapsize, "Copy-on-write memory map data not written correctly.") m.flush() verify(open(TESTFN, "rb").read() == "c" * mapsize, "Copy-on-write test data file should not be modified.") try: print " Ensuring copy-on-write maps cannot be resized." m.resize(2 * mapsize) except TypeError: pass else: verify(0, "Copy-on-write mmap resize did not raise exception.") del m, f try: print " Ensuring invalid access parameter raises exception." f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize, access=4) except ValueError: pass else: verify(0, "Invalid access code should have raised exception.") if os.name == "posix": # Try incompatible flags, prot and access parameters. f = open(TESTFN, "r+b") try: m = mmap.mmap( f.fileno(), mapsize, flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE ) except ValueError: pass else: verify(0, "Incompatible parameters should raise ValueError.") f.close() finally: try: os.unlink(TESTFN) except OSError: pass # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2, # searching for data with embedded \0 bytes didn't work. f = open(TESTFN, "w+") try: # unlink TESTFN no matter what data = "aabaac\x00deef\x00\x00aa\x00" n = len(data) f.write(data) f.flush() m = mmap.mmap(f.fileno(), n) f.close() for start in range(n + 1): for finish in range(start, n + 1): slice = data[start:finish] vereq(m.find(slice), data.find(slice)) vereq(m.find(slice + "x"), -1) m.close() finally: os.unlink(TESTFN) # make sure a double close doesn't crash on Solaris (Bug# 665913) f = open(TESTFN, "w+") try: # unlink TESTFN no matter what f.write(2 ** 16 * "a") # Arbitrary character f.close() f = open(TESTFN) mf = mmap.mmap(f.fileno(), 2 ** 16, access=mmap.ACCESS_READ) mf.close() mf.close() f.close() finally: os.unlink(TESTFN) print " Test passed"
from test.test_support import verify, vereq, verbose, TestFailed import sys module = type(sys) # An uninitialized module has no __dict__ or __name__, and __doc__ is None foo = module.__new__(module) verify(foo.__dict__ is None) try: s = foo.__name__ except AttributeError: pass else: raise TestFailed, "__name__ = %s" % repr(s) vereq(foo.__doc__, module.__doc__) # Regularly initialized module, no docstring foo = module("foo") vereq(foo.__name__, "foo") vereq(foo.__doc__, None) vereq(foo.__dict__, {"__name__": "foo", "__doc__": None}) # ASCII docstring foo = module("foo", "foodoc") vereq(foo.__name__, "foo") vereq(foo.__doc__, "foodoc") vereq(foo.__dict__, {"__name__": "foo", "__doc__": "foodoc"}) # Unicode docstring foo = module("foo", u"foodoc\u1234")
def test_unpack_from(): test_string = 'abcd01234' fmt = '4s' s = struct.Struct(fmt) for cls in (str, buffer): data = cls(test_string) vereq(s.unpack_from(data), ('abcd', )) vereq(s.unpack_from(data, 2), ('cd01', )) vereq(s.unpack_from(data, 4), ('0123', )) for i in xrange(6): vereq(s.unpack_from(data, i), (data[i:i + 4], )) for i in xrange(6, len(test_string) + 1): simple_err(s.unpack_from, data, i) for cls in (str, buffer): data = cls(test_string) vereq(struct.unpack_from(fmt, data), ('abcd', )) vereq(struct.unpack_from(fmt, data, 2), ('cd01', )) vereq(struct.unpack_from(fmt, data, 4), ('0123', )) for i in xrange(6): vereq(struct.unpack_from(fmt, data, i), (data[i:i + 4], )) for i in xrange(6, len(test_string) + 1): simple_err(struct.unpack_from, fmt, data, i)
from test.test_support import vereq import time t = time.gmtime() astuple = tuple(t) vereq(len(t), len(astuple)) vereq(t, astuple) # Check that slicing works the same way; at one point, slicing t[i:j] with # 0 < i < j could produce NULLs in the result. for i in range(-len(t), len(t)): for j in range(-len(t), len(t)): vereq(t[i:j], astuple[i:j]) # Devious code could crash structseqs' contructors class C: def __getitem__(self, i): raise IndexError def __len__(self): return 9 try: repr(time.struct_time(C())) except: pass # XXX more needed
def test_both(): "Test mmap module on Unix systems and Windows" # Create a file to be mmap'ed. if os.path.exists(TESTFN): os.unlink(TESTFN) f = open(TESTFN, 'w+') try: # unlink TESTFN no matter what # Write 2 pages worth of data to the file f.write('\0'* PAGESIZE) f.write('foo') f.write('\0'* (PAGESIZE-3) ) f.flush() m = mmap.mmap(f.fileno(), 2 * PAGESIZE) f.close() # Simple sanity checks print type(m) # SF bug 128713: segfaulted on Linux print ' Position of foo:', m.find('foo') / float(PAGESIZE), 'pages' vereq(m.find('foo'), PAGESIZE) print ' Length of file:', len(m) / float(PAGESIZE), 'pages' vereq(len(m), 2*PAGESIZE) print ' Contents of byte 0:', repr(m[0]) vereq(m[0], '\0') print ' Contents of first 3 bytes:', repr(m[0:3]) vereq(m[0:3], '\0\0\0') # Modify the file's content print "\n Modifying file's content..." m[0] = '3' m[PAGESIZE +3: PAGESIZE +3+3] = 'bar' # Check that the modification worked print ' Contents of byte 0:', repr(m[0]) vereq(m[0], '3') print ' Contents of first 3 bytes:', repr(m[0:3]) vereq(m[0:3], '3\0\0') print ' Contents of second page:', repr(m[PAGESIZE-1 : PAGESIZE + 7]) vereq(m[PAGESIZE-1 : PAGESIZE + 7], '\0foobar\0') m.flush() # Test doing a regular expression match in an mmap'ed file match = re.search('[A-Za-z]+', m) if match is None: print ' ERROR: regex match on mmap failed!' else: start, end = match.span(0) length = end - start print ' Regex match on mmap (page start, length of match):', print start / float(PAGESIZE), length vereq(start, PAGESIZE) vereq(end, PAGESIZE + 6) # test seeking around (try to overflow the seek implementation) m.seek(0,0) print ' Seek to zeroth byte' vereq(m.tell(), 0) m.seek(42,1) print ' Seek to 42nd byte' vereq(m.tell(), 42) m.seek(0,2) print ' Seek to last byte' vereq(m.tell(), len(m)) print ' Try to seek to negative position...' try: m.seek(-1) except ValueError: pass else: verify(0, 'expected a ValueError but did not get it') print ' Try to seek beyond end of mmap...' try: m.seek(1,2) except ValueError: pass else: verify(0, 'expected a ValueError but did not get it') print ' Try to seek to negative position...' try: m.seek(-len(m)-1,2) except ValueError: pass else: verify(0, 'expected a ValueError but did not get it') # Try resizing map print ' Attempting resize()' try: m.resize(512) except SystemError: # resize() not supported # No messages are printed, since the output of this test suite # would then be different across platforms. pass else: # resize() is supported verify(len(m) == 512, "len(m) is %d, but expecting 512" % (len(m),) ) # Check that we can no longer seek beyond the new size. try: m.seek(513,0) except ValueError: pass else: verify(0, 'Could seek beyond the new size') # Check that the underlying file is truncated too # (bug #728515) f = open(TESTFN) f.seek(0, 2) verify(f.tell() == 512, 'Underlying file not truncated') f.close() verify(m.size() == 512, 'New size not reflected in file') m.close() finally: try: f.close() except OSError: pass try: os.unlink(TESTFN) except OSError: pass # Test for "access" keyword parameter try: mapsize = 10 print " Creating", mapsize, "byte test data file." open(TESTFN, "wb").write("a"*mapsize) print " Opening mmap with access=ACCESS_READ" f = open(TESTFN, "rb") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ) verify(m[:] == 'a'*mapsize, "Readonly memory map data incorrect.") print " Ensuring that readonly mmap can't be slice assigned." try: m[:] = 'b'*mapsize except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be item assigned." try: m[0] = 'b' except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be write() to." try: m.seek(0,0) m.write('abc') except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be write_byte() to." try: m.seek(0,0) m.write_byte('d') except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be resized." try: m.resize(2*mapsize) except SystemError: # resize is not universally supported pass except TypeError: pass else: verify(0, "Able to resize readonly memory map") del m, f verify(open(TESTFN, "rb").read() == 'a'*mapsize, "Readonly memory map data file was modified") print " Opening mmap with size too big" import sys f = open(TESTFN, "r+b") try: m = mmap.mmap(f.fileno(), mapsize+1) except ValueError: # we do not expect a ValueError on Windows # CAUTION: This also changes the size of the file on disk, and # later tests assume that the length hasn't changed. We need to # repair that. if sys.platform.startswith('win'): verify(0, "Opening mmap with size+1 should work on Windows.") else: # we expect a ValueError on Unix, but not on Windows if not sys.platform.startswith('win'): verify(0, "Opening mmap with size+1 should raise ValueError.") m.close() f.close() if sys.platform.startswith('win'): # Repair damage from the resizing test. f = open(TESTFN, 'r+b') f.truncate(mapsize) f.close() print " Opening mmap with access=ACCESS_WRITE" f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE) print " Modifying write-through memory map." m[:] = 'c'*mapsize verify(m[:] == 'c'*mapsize, "Write-through memory map memory not updated properly.") m.flush() m.close() f.close() f = open(TESTFN, 'rb') stuff = f.read() f.close() verify(stuff == 'c'*mapsize, "Write-through memory map data file not updated properly.") print " Opening mmap with access=ACCESS_COPY" f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY) print " Modifying copy-on-write memory map." m[:] = 'd'*mapsize verify(m[:] == 'd' * mapsize, "Copy-on-write memory map data not written correctly.") m.flush() verify(open(TESTFN, "rb").read() == 'c'*mapsize, "Copy-on-write test data file should not be modified.") try: print " Ensuring copy-on-write maps cannot be resized." m.resize(2*mapsize) except TypeError: pass else: verify(0, "Copy-on-write mmap resize did not raise exception.") del m, f try: print " Ensuring invalid access parameter raises exception." f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize, access=4) except ValueError: pass else: verify(0, "Invalid access code should have raised exception.") if os.name == "posix": # Try incompatible flags, prot and access parameters. f = open(TESTFN, "r+b") try: m = mmap.mmap(f.fileno(), mapsize, flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE) except ValueError: pass else: verify(0, "Incompatible parameters should raise ValueError.") f.close() finally: try: os.unlink(TESTFN) except OSError: pass print ' Try opening a bad file descriptor...' try: mmap.mmap(-2, 4096) except mmap.error: pass else: verify(0, 'expected a mmap.error but did not get it') # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2, # searching for data with embedded \0 bytes didn't work. f = open(TESTFN, 'w+') try: # unlink TESTFN no matter what data = 'aabaac\x00deef\x00\x00aa\x00' n = len(data) f.write(data) f.flush() m = mmap.mmap(f.fileno(), n) f.close() for start in range(n+1): for finish in range(start, n+1): slice = data[start : finish] vereq(m.find(slice), data.find(slice)) vereq(m.find(slice + 'x'), -1) m.close() finally: os.unlink(TESTFN) # make sure a double close doesn't crash on Solaris (Bug# 665913) f = open(TESTFN, 'w+') try: # unlink TESTFN no matter what f.write(2**16 * 'a') # Arbitrary character f.close() f = open(TESTFN) mf = mmap.mmap(f.fileno(), 2**16, access=mmap.ACCESS_READ) mf.close() mf.close() f.close() finally: os.unlink(TESTFN) # test mapping of entire file by passing 0 for map length if hasattr(os, "stat"): print " Ensuring that passing 0 as map length sets map size to current file size." f = open(TESTFN, "w+") try: f.write(2**16 * 'm') # Arbitrary character f.close() f = open(TESTFN, "rb+") mf = mmap.mmap(f.fileno(), 0) verify(len(mf) == 2**16, "Map size should equal file size.") vereq(mf.read(2**16), 2**16 * "m") mf.close() f.close() finally: os.unlink(TESTFN) # test mapping of entire file by passing 0 for map length if hasattr(os, "stat"): print " Ensuring that passing 0 as map length sets map size to current file size." f = open(TESTFN, "w+") try: f.write(2**16 * 'm') # Arbitrary character f.close() f = open(TESTFN, "rb+") mf = mmap.mmap(f.fileno(), 0) verify(len(mf) == 2**16, "Map size should equal file size.") vereq(mf.read(2**16), 2**16 * "m") mf.close() f.close() finally: os.unlink(TESTFN) # make move works everywhere (64-bit format problem earlier) f = open(TESTFN, 'w+') try: # unlink TESTFN no matter what f.write("ABCDEabcde") # Arbitrary character f.flush() mf = mmap.mmap(f.fileno(), 10) mf.move(5, 0, 5) verify(mf[:] == "ABCDEABCDE", "Map move should have duplicated front 5") mf.close() f.close() finally: os.unlink(TESTFN) # Test that setting access to PROT_READ gives exception # rather than crashing if hasattr(mmap, "PROT_READ"): try: mapsize = 10 open(TESTFN, "wb").write("a"*mapsize) f = open(TESTFN, "rb") m = mmap.mmap(f.fileno(), mapsize, prot=mmap.PROT_READ) try: m.write("foo") except TypeError: pass else: verify(0, "PROT_READ is not working") finally: os.unlink(TESTFN)
def test_both(): "Test mmap module on Unix systems and Windows" # Create a file to be mmap'ed. if os.path.exists(TESTFN): os.unlink(TESTFN) f = open(TESTFN, 'w+') try: # unlink TESTFN no matter what # Write 2 pages worth of data to the file f.write('\0' * PAGESIZE) f.write('foo') f.write('\0' * (PAGESIZE - 3)) f.flush() m = mmap.mmap(f.fileno(), 2 * PAGESIZE) f.close() # Simple sanity checks print type(m) # SF bug 128713: segfaulted on Linux print ' Position of foo:', m.find('foo') / float(PAGESIZE), 'pages' vereq(m.find('foo'), PAGESIZE) print ' Length of file:', len(m) / float(PAGESIZE), 'pages' vereq(len(m), 2 * PAGESIZE) print ' Contents of byte 0:', repr(m[0]) vereq(m[0], '\0') print ' Contents of first 3 bytes:', repr(m[0:3]) vereq(m[0:3], '\0\0\0') # Modify the file's content print "\n Modifying file's content..." m[0] = '3' m[PAGESIZE + 3:PAGESIZE + 3 + 3] = 'bar' # Check that the modification worked print ' Contents of byte 0:', repr(m[0]) vereq(m[0], '3') print ' Contents of first 3 bytes:', repr(m[0:3]) vereq(m[0:3], '3\0\0') print ' Contents of second page:', repr(m[PAGESIZE - 1:PAGESIZE + 7]) vereq(m[PAGESIZE - 1:PAGESIZE + 7], '\0foobar\0') m.flush() # Test doing a regular expression match in an mmap'ed file match = re.search('[A-Za-z]+', m) if match is None: print ' ERROR: regex match on mmap failed!' else: start, end = match.span(0) length = end - start print ' Regex match on mmap (page start, length of match):', print start / float(PAGESIZE), length vereq(start, PAGESIZE) vereq(end, PAGESIZE + 6) # test seeking around (try to overflow the seek implementation) m.seek(0, 0) print ' Seek to zeroth byte' vereq(m.tell(), 0) m.seek(42, 1) print ' Seek to 42nd byte' vereq(m.tell(), 42) m.seek(0, 2) print ' Seek to last byte' vereq(m.tell(), len(m)) print ' Try to seek to negative position...' try: m.seek(-1) except ValueError: pass else: verify(0, 'expected a ValueError but did not get it') print ' Try to seek beyond end of mmap...' try: m.seek(1, 2) except ValueError: pass else: verify(0, 'expected a ValueError but did not get it') print ' Try to seek to negative position...' try: m.seek(-len(m) - 1, 2) except ValueError: pass else: verify(0, 'expected a ValueError but did not get it') # Try resizing map print ' Attempting resize()' try: m.resize(512) except SystemError: # resize() not supported # No messages are printed, since the output of this test suite # would then be different across platforms. pass else: # resize() is supported verify( len(m) == 512, "len(m) is %d, but expecting 512" % (len(m), )) # Check that we can no longer seek beyond the new size. try: m.seek(513, 0) except ValueError: pass else: verify(0, 'Could seek beyond the new size') # Check that the underlying file is truncated too # (bug #728515) f = open(TESTFN) f.seek(0, 2) verify(f.tell() == 512, 'Underlying file not truncated') f.close() verify(m.size() == 512, 'New size not reflected in file') m.close() finally: try: f.close() except OSError: pass try: os.unlink(TESTFN) except OSError: pass # Test for "access" keyword parameter try: mapsize = 10 print " Creating", mapsize, "byte test data file." open(TESTFN, "wb").write("a" * mapsize) print " Opening mmap with access=ACCESS_READ" f = open(TESTFN, "rb") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_READ) verify(m[:] == 'a' * mapsize, "Readonly memory map data incorrect.") print " Ensuring that readonly mmap can't be slice assigned." try: m[:] = 'b' * mapsize except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be item assigned." try: m[0] = 'b' except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be write() to." try: m.seek(0, 0) m.write('abc') except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be write_byte() to." try: m.seek(0, 0) m.write_byte('d') except TypeError: pass else: verify(0, "Able to write to readonly memory map") print " Ensuring that readonly mmap can't be resized." try: m.resize(2 * mapsize) except SystemError: # resize is not universally supported pass except TypeError: pass else: verify(0, "Able to resize readonly memory map") del m, f verify( open(TESTFN, "rb").read() == 'a' * mapsize, "Readonly memory map data file was modified") print " Opening mmap with size too big" import sys f = open(TESTFN, "r+b") try: m = mmap.mmap(f.fileno(), mapsize + 1) except ValueError: # we do not expect a ValueError on Windows # CAUTION: This also changes the size of the file on disk, and # later tests assume that the length hasn't changed. We need to # repair that. if sys.platform.startswith('win'): verify(0, "Opening mmap with size+1 should work on Windows.") else: # we expect a ValueError on Unix, but not on Windows if not sys.platform.startswith('win'): verify(0, "Opening mmap with size+1 should raise ValueError.") m.close() f.close() if sys.platform.startswith('win'): # Repair damage from the resizing test. f = open(TESTFN, 'r+b') f.truncate(mapsize) f.close() print " Opening mmap with access=ACCESS_WRITE" f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_WRITE) print " Modifying write-through memory map." m[:] = 'c' * mapsize verify(m[:] == 'c' * mapsize, "Write-through memory map memory not updated properly.") m.flush() m.close() f.close() f = open(TESTFN, 'rb') stuff = f.read() f.close() verify(stuff == 'c' * mapsize, "Write-through memory map data file not updated properly.") print " Opening mmap with access=ACCESS_COPY" f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize, access=mmap.ACCESS_COPY) print " Modifying copy-on-write memory map." m[:] = 'd' * mapsize verify(m[:] == 'd' * mapsize, "Copy-on-write memory map data not written correctly.") m.flush() verify( open(TESTFN, "rb").read() == 'c' * mapsize, "Copy-on-write test data file should not be modified.") try: print " Ensuring copy-on-write maps cannot be resized." m.resize(2 * mapsize) except TypeError: pass else: verify(0, "Copy-on-write mmap resize did not raise exception.") del m, f try: print " Ensuring invalid access parameter raises exception." f = open(TESTFN, "r+b") m = mmap.mmap(f.fileno(), mapsize, access=4) except ValueError: pass else: verify(0, "Invalid access code should have raised exception.") if os.name == "posix": # Try incompatible flags, prot and access parameters. f = open(TESTFN, "r+b") try: m = mmap.mmap(f.fileno(), mapsize, flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ, access=mmap.ACCESS_WRITE) except ValueError: pass else: verify(0, "Incompatible parameters should raise ValueError.") f.close() finally: try: os.unlink(TESTFN) except OSError: pass print ' Try opening a bad file descriptor...' try: mmap.mmap(-2, 4096) except mmap.error: pass else: verify(0, 'expected a mmap.error but did not get it') # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2, # searching for data with embedded \0 bytes didn't work. f = open(TESTFN, 'w+') try: # unlink TESTFN no matter what data = 'aabaac\x00deef\x00\x00aa\x00' n = len(data) f.write(data) f.flush() m = mmap.mmap(f.fileno(), n) f.close() for start in range(n + 1): for finish in range(start, n + 1): slice = data[start:finish] vereq(m.find(slice), data.find(slice)) vereq(m.find(slice + 'x'), -1) m.close() finally: os.unlink(TESTFN) # make sure a double close doesn't crash on Solaris (Bug# 665913) f = open(TESTFN, 'w+') try: # unlink TESTFN no matter what f.write(2**16 * 'a') # Arbitrary character f.close() f = open(TESTFN) mf = mmap.mmap(f.fileno(), 2**16, access=mmap.ACCESS_READ) mf.close() mf.close() f.close() finally: os.unlink(TESTFN) # test mapping of entire file by passing 0 for map length if hasattr(os, "stat"): print " Ensuring that passing 0 as map length sets map size to current file size." f = open(TESTFN, "w+") try: f.write(2**16 * 'm') # Arbitrary character f.close() f = open(TESTFN, "rb+") mf = mmap.mmap(f.fileno(), 0) verify(len(mf) == 2**16, "Map size should equal file size.") vereq(mf.read(2**16), 2**16 * "m") mf.close() f.close() finally: os.unlink(TESTFN) # test mapping of entire file by passing 0 for map length if hasattr(os, "stat"): print " Ensuring that passing 0 as map length sets map size to current file size." f = open(TESTFN, "w+") try: f.write(2**16 * 'm') # Arbitrary character f.close() f = open(TESTFN, "rb+") mf = mmap.mmap(f.fileno(), 0) verify(len(mf) == 2**16, "Map size should equal file size.") vereq(mf.read(2**16), 2**16 * "m") mf.close() f.close() finally: os.unlink(TESTFN) # make move works everywhere (64-bit format problem earlier) f = open(TESTFN, 'w+') try: # unlink TESTFN no matter what f.write("ABCDEabcde") # Arbitrary character f.flush() mf = mmap.mmap(f.fileno(), 10) mf.move(5, 0, 5) verify(mf[:] == "ABCDEABCDE", "Map move should have duplicated front 5") mf.close() f.close() finally: os.unlink(TESTFN)
from test.test_support import vereq, TestFailed def check_conversion(num): mpz_num = mpz.mpz(num) vereq(int(mpz_num), num) vereq(long(mpz_num), num) vereq(str(mpz_num), 'mpz(%s)' % ` int(num) `) check_conversion(10) check_conversion(10L) # FIXME: should check strings, but I'm not sure it works, this seems odd: # mpz.mpz('10') == mpz(12337) vereq(mpz.divm(100, 200, 3), 2) vereq(mpz.divm(100L, 200, 3), 2) vereq(mpz.divm(100, 200L, 3), 2) vereq(mpz.divm(100L, 200L, 3), 2) vereq(mpz.gcd(100, 200), 100) vereq(mpz.gcd(100L, 200), 100) vereq(mpz.gcd(100, 200L), 100) vereq(mpz.gcd(100L, 200L), 100) vereq(mpz.gcdext(100, 200), (100, 1, 0)) vereq(mpz.gcdext(100L, 200), (100, 1, 0)) vereq(mpz.gcdext(100, 200L), (100, 1, 0)) vereq(mpz.gcdext(100L, 200L), (100, 1, 0)) vereq(mpz.powm(100, 0, 3), 1)