def test_im_doc(): class C: def foo(self): "hello" verify(C.foo.__doc__ == "hello") verify(C().foo.__doc__ == "hello") cantset(C.foo, "__doc__", "hello") cantset(C().foo, "__doc__", "hello")
def test_logs(): import math if verbose: print "log and log10" LOG10E = math.log10(math.e) for exp in range(10) + [100, 1000, 10000]: value = 10 ** exp log10 = math.log10(value) verify(fcmp(log10, exp) == 0) # log10(value) == exp, so log(value) == log10(value)/log10(e) == # exp/LOG10E expected = exp / LOG10E log = math.log(value) verify(fcmp(log, expected) == 0) for bad in -(1L << 10000), -2L, 0L: try: math.log(bad) raise TestFailed("expected ValueError from log(<= 0)") except ValueError: pass try: math.log10(bad) raise TestFailed("expected ValueError from log10(<= 0)") except ValueError: pass
def test_im_class(): class C: def foo(self): pass verify(C.foo.im_class is C) verify(C().foo.im_class is C) cantset(C.foo, "im_class", C) cantset(C().foo, "im_class", C)
def check_all(modname): names = {} try: exec "import %s" % modname in names except ImportError: # Silent fail here seems the best route since some modules # may not be available in all environments. # Since an ImportError may leave a partial module object in # sys.modules, get rid of that first. Here's what happens if # you don't: importing pty fails on Windows because pty tries to # import FCNTL, which doesn't exist. That raises an ImportError, # caught here. It also leaves a partial pty module in sys.modules. # So when test_pty is called later, the import of pty succeeds, # but shouldn't. As a result, test_pty crashes with an # AttributeError instead of an ImportError, and regrtest interprets # the latter as a test failure (ImportError is treated as "test # skipped" -- which is what test_pty should say on Windows). try: del sys.modules[modname] except KeyError: pass return verify(hasattr(sys.modules[modname], "__all__"), "%s has no __all__ attribute" % modname) names = {} exec "from %s import *" % modname in names if names.has_key("__builtins__"): del names["__builtins__"] keys = names.keys() keys.sort() all = list(sys.modules[modname].__all__) # in case it's a tuple all.sort() verify(keys==all, "%s != %s" % (keys, all))
def test_im_name(): class C: def foo(self): pass verify(C.foo.__name__ == "foo") verify(C().foo.__name__ == "foo") cantset(C.foo, "__name__", "foo") cantset(C().foo, "__name__", "foo")
def drive_one(pattern, length): q, r = divmod(length, len(pattern)) teststring = pattern * q + pattern[:r] verify(len(teststring) == length) try_one(teststring) try_one(teststring + "x") try_one(teststring[:-1])
def test_float_overflow(): import math if verbose: print "long->float overflow" for x in -2.0, -1.0, 0.0, 1.0, 2.0: verify(float(long(x)) == x) shuge = '12345' * 1000 huge = 1L << 30000 mhuge = -huge namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math} for test in ["float(huge)", "float(mhuge)", "complex(huge)", "complex(mhuge)", "complex(huge, 1)", "complex(mhuge, 1)", "complex(1, huge)", "complex(1, mhuge)", "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.", "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.", "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.", "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.", "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.", "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.", "math.sin(huge)", "math.sin(mhuge)", "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better "math.floor(huge)", "math.floor(mhuge)", "float(shuge) == long(shuge)"]: try: eval(test, namespace) except OverflowError: pass else: raise TestFailed("expected OverflowError from %s" % test)
def test_func_code(): def f(): pass def g(): print 12 #XXX: changed to isinstance for jython #verify(type(f.func_code) is types.CodeType) verify(isinstance(f.func_code, types.CodeType)) f.func_code = g.func_code cantset(f, "func_code", None)
def test_im_self(): class C: def foo(self): pass verify(C.foo.im_self is None) c = C() verify(c.foo.im_self is c) cantset(C.foo, "im_self", None) cantset(c.foo, "im_self", c)
def test_im_dict(): class C: def foo(self): pass foo.bar = 42 verify(C.foo.__dict__ == {'bar': 42}) verify(C().foo.__dict__ == {'bar': 42}) cantset(C.foo, "__dict__", C.foo.__dict__) cantset(C().foo, "__dict__", C.foo.__dict__)
def testdgram(proto, addr): s = socket.socket(proto, socket.SOCK_DGRAM) s.sendto(teststring, addr) buf = data = receive(s, 100) while data and '\n' not in buf: data = receive(s, 100) buf += data verify(buf == teststring) s.close()
def test_im_func(): def foo(self): pass class C: pass C.foo = foo verify(C.foo.im_func is foo) verify(C().foo.im_func is foo) cantset(C.foo, "im_func", foo) cantset(C().foo, "im_func", foo)
def teststream(proto, addr): s = socket.socket(proto, socket.SOCK_STREAM) s.connect(addr) s.sendall(teststring) buf = data = receive(s, 100) while data and '\n' not in buf: data = receive(s, 100) buf += data verify(buf == teststring) s.close()
def test(openmethod, what): if verbose: print '\nTesting: ', what fname = tempfile.mktemp() f = openmethod(fname, 'c') verify(f.keys() == []) if verbose: print 'creation...' f['0'] = '' f['a'] = 'Guido' f['b'] = 'van' f['c'] = 'Rossum' f['d'] = 'invented' f['f'] = 'Python' if verbose: print '%s %s %s' % (f['a'], f['b'], f['c']) if what == 'BTree' : if verbose: print 'key ordering...' f.set_location(f.first()[0]) while 1: try: rec = f.next() except KeyError: if rec != f.last(): print 'Error, last != last!' f.previous() break if verbose: print rec if not f.has_key('a'): print 'Error, missing key!' f.sync() f.close() if verbose: print 'modification...' f = openmethod(fname, 'w') f['d'] = 'discovered' if verbose: print 'access...' for key in f.keys(): word = f[key] if verbose: print word f.close() try: os.remove(fname) except os.error: pass
def query_errors(): print "Testing query interface..." cf = ConfigParser.ConfigParser() verify(cf.sections() == [], "new ConfigParser should have no defined sections") verify(not cf.has_section("Foo"), "new ConfigParser should have no acknowledged sections") try: cf.options("Foo") except ConfigParser.NoSectionError, e: pass
def dicts(): # Verify that __eq__ and __ne__ work for dicts even if the keys and # values don't support anything other than __eq__ and __ne__. Complex # numbers are a fine example of that. import random imag1a = {} for i in range(50): imag1a[random.randrange(100)*1j] = random.randrange(100)*1j items = imag1a.items() random.shuffle(items) imag1b = {} for k, v in items: imag1b[k] = v imag2 = imag1b.copy() imag2[k] = v + 1.0 verify(imag1a == imag1a, "imag1a == imag1a should have worked") verify(imag1a == imag1b, "imag1a == imag1b should have worked") verify(imag2 == imag2, "imag2 == imag2 should have worked") verify(imag1a != imag2, "imag1a != imag2 should have worked") for op in "<", "<=", ">", ">=": try: eval("imag1a %s imag2" % op) except TypeError: pass else: raise TestFailed("expected TypeError from imag1a %s imag2" % op)
def SimpleQueueTest(q): if not q.empty(): raise RuntimeError, "Call this function with an empty queue" # I guess we better check things actually queue correctly a little :) q.put(111) q.put(222) verify(q.get()==111 and q.get()==222, "Didn't seem to queue the correct data!") for i in range(queue_size-1): q.put(i) verify(not q.full(), "Queue should not be full") q.put("last") verify(q.full(), "Queue should be full") try: q.put("full", block=0) raise TestFailed("Didn't appear to block with a full queue") except Queue.Full: pass # Test a blocking put _doBlockingTest( q.put, ("full",), q.get, ()) # Empty it for i in range(queue_size): q.get() verify(q.empty(), "Queue should be empty") try: q.get(block=0) raise TestFailed("Didn't appear to block with an empty queue") except Queue.Empty: pass # Test a blocking get _doBlockingTest( q.get, (), q.put, ('empty',))
def cantset(obj, name, value): verify(hasattr(obj, name)) # Otherwise it's probably a typo try: setattr(obj, name, value) except (AttributeError, TypeError): pass else: raise TestFailed, "shouldn't be able to set %s to %r" % (name, value) try: delattr(obj, name) except (AttributeError, TypeError): pass else: raise TestFailed, "shouldn't be able to del %s" % name
def __init__(self, formatpair, bytesize): assert len(formatpair) == 2 self.formatpair = formatpair for direction in "<>!=": for code in formatpair: format = direction + code verify(struct.calcsize(format) == bytesize) self.bytesize = bytesize self.bitsize = bytesize * 8 self.signed_code, self.unsigned_code = formatpair self.unsigned_min = 0 self.unsigned_max = 2L**self.bitsize - 1 self.signed_min = -(2L**(self.bitsize-1)) self.signed_max = 2L**(self.bitsize-1) - 1
def write(src): print "Testing writing of files..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) output = StringIO.StringIO() cf.write(output) verify(output, """[DEFAULT] foo = another very long line [Long Line] foo = this line is much, much longer than my editor likes it. """)
def test_poll1(): """Basic functional test of poll object Create a bunch of pipe and test that poll works with them. """ print 'Running poll test 1' p = select.poll() NUM_PIPES = 12 MSG = " This is a test." MSG_LEN = len(MSG) readers = [] writers = [] r2w = {} w2r = {} for i in range(NUM_PIPES): rd, wr = os.pipe() p.register(rd, select.POLLIN) p.register(wr, select.POLLOUT) readers.append(rd) writers.append(wr) r2w[rd] = wr w2r[wr] = rd while writers: ready = p.poll() ready_writers = find_ready_matching(ready, select.POLLOUT) if not ready_writers: raise RuntimeError, "no pipes ready for writing" wr = random.choice(ready_writers) os.write(wr, MSG) ready = p.poll() ready_readers = find_ready_matching(ready, select.POLLIN) if not ready_readers: raise RuntimeError, "no pipes ready for reading" rd = random.choice(ready_readers) buf = os.read(rd, MSG_LEN) verify(len(buf) == MSG_LEN) print buf os.close(r2w[rd]) ; os.close( rd ) p.unregister( r2w[rd] ) p.unregister( rd ) writers.remove(r2w[rd]) poll_unit_tests() print 'Poll test 1 complete'
def boolean(src): print "Testing interpretation of boolean Values..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) for x in range(1, 5): verify(cf.getboolean('BOOLTEST', 't%d' % (x)) == 1) for x in range(1, 5): verify(cf.getboolean('BOOLTEST', 'f%d' % (x)) == 0) for x in range(1, 5): try: cf.getboolean('BOOLTEST', 'e%d' % (x)) except ValueError: pass else: raise TestFailed( "getboolean() failed to report a non boolean value")
def test_func_defaults(): def f(a, b): return (a, b) verify(f.func_defaults is None) #XXX: setting defaults this way is not yet supported in jython. if not sys.platform.startswith("java"): f.func_defaults = (1, 2) verify(f.func_defaults == (1, 2)) verify(f(10) == (10, 2)) def g(a=1, b=2): return (a, b) verify(g.func_defaults == (1, 2)) del g.func_defaults verify(g.func_defaults is None) try: g() except TypeError: pass else: raise TestFailed, "shouldn't be allowed to call g() w/o defaults"
def interpolation(src): print "Testing value interpolation..." cf = ConfigParser.ConfigParser({"getname": "%(__name__)s"}) sio = StringIO.StringIO(src) cf.readfp(sio) verify(cf.get("Foo", "getname") == "Foo") verify(cf.get("Foo", "bar") == "something with interpolation (1 step)") verify(cf.get("Foo", "bar9") == "something with lots of interpolation (9 steps)") verify(cf.get("Foo", "bar10") == "something with lots of interpolation (10 steps)") expect_get_error(cf, ConfigParser.InterpolationDepthError, "Foo", "bar11")
def test(): if verbose: print "disabling automatic collection" enabled = gc.isenabled() gc.disable() verify(not gc.isenabled() ) debug = gc.get_debug() gc.set_debug(debug & ~gc.DEBUG_LEAK) # this test is supposed to leak try: test_all() finally: gc.set_debug(debug) # test gc.enable() even if GC is disabled by default if verbose: print "restoring automatic collection" # make sure to always test gc.enable() gc.enable() verify(gc.isenabled()) if not enabled: gc.disable()
def test_native_qQ(): bytes = struct.calcsize('q') # The expected values here are in big-endian format, primarily because # I'm on a little-endian machine and so this is the clearest way (for # me) to force the code to get exercised. for format, input, expected in ( ('q', -1, '\xff' * bytes), ('q', 0, '\x00' * bytes), ('Q', 0, '\x00' * bytes), ('q', 1L, '\x00' * (bytes-1) + '\x01'), ('Q', (1L << (8*bytes))-1, '\xff' * bytes), ('q', (1L << (8*bytes-1))-1, '\x7f' + '\xff' * (bytes - 1))): got = struct.pack(format, input) native_expected = bigendian_to_native(expected) verify(got == native_expected, "%r-pack of %r gave %r, not %r" % (format, input, got, native_expected)) retrieved = struct.unpack(format, got)[0] verify(retrieved == input, "%r-unpack of %r gave %r, not %r" % (format, got, retrieved, input))
def DeleteTestData(root_key): key = OpenKey(root_key, test_key_name, 0, KEY_ALL_ACCESS) sub_key = OpenKey(key, "sub_key", 0, KEY_ALL_ACCESS) # It is not necessary to delete the values before deleting # the key (although subkeys must not exist). We delete them # manually just to prove we can :-) for value_name, value_data, value_type in test_data: DeleteValue(sub_key, value_name) nkeys, nvalues, since_mod = QueryInfoKey(sub_key) verify(nkeys==0 and nvalues==0, "subkey not empty before delete") sub_key.Close() DeleteKey(key, "sub_key") try: # Shouldnt be able to delete it twice! DeleteKey(key, "sub_key") verify(0, "Deleting the key twice succeeded") except EnvironmentError: pass key.Close() DeleteKey(root_key, test_key_name) # Opening should now fail! try: key = OpenKey(root_key, test_key_name) verify(0, "Could open the non-existent key") except WindowsError: # Use this error name this time pass
def main(): for i in range(NUM_THREADS): thread.start_new(f, (i,)) time.sleep(LONGSLEEP) a = alive.keys() a.sort() verify(a == range(NUM_THREADS)) prefork_lives = alive.copy() if sys.platform in ['unixware7']: cpid = os.fork1() else: cpid = os.fork() if cpid == 0: # Child time.sleep(LONGSLEEP) n = 0 for key in alive.keys(): if alive[key] != prefork_lives[key]: n = n+1 os._exit(n) else: # Parent spid, status = os.waitpid(cpid, 0) verify(spid == cpid) verify(status == 0, "cause = %d, exit = %d" % (status&0xff, status>>8) ) global stop # Tell threads to die stop = 1 time.sleep(2*SHORTSLEEP) # Wait for threads to die
def test_func_closure(): a = 12 def f(): print a c = f.func_closure verify(isinstance(c, tuple)) verify(len(c) == 1) verify(c[0].__class__.__name__ == "cell") # don't have a type object handy cantset(f, "func_closure", c)
def test_705836(): import math for base in range(1, 33): # smaller <- largest representable float less than base. delta = 0.5 while base - delta / 2.0 != base: delta /= 2.0 smaller = base - delta # Packing this rounds away a solid string of trailing 1 bits. packed = struct.pack("<f", smaller) unpacked = struct.unpack("<f", packed)[0] # This failed at base = 2, 4, and 32, with unpacked = 1, 2, and # 16, respectively. verify(base == unpacked) bigpacked = struct.pack(">f", smaller) verify(bigpacked == string_reverse(packed), ">f pack should be byte-reversal of <f pack") unpacked = struct.unpack(">f", bigpacked)[0] verify(base == unpacked) # Largest finite IEEE single. big = (1 << 24) - 1 big = math.ldexp(big, 127 - 23) packed = struct.pack(">f", big) unpacked = struct.unpack(">f", packed)[0] verify(big == unpacked) # The same, but tack on a 1 bit so it rounds up to infinity. big = (1 << 25) - 1 big = math.ldexp(big, 127 - 24) try: packed = struct.pack(">f", big) except OverflowError: pass else: TestFailed("expected OverflowError")
#! /usr/bin/env python from test_support import verbose, verify from types import TupleType, StringType, IntType import __future__ GOOD_SERIALS = ("alpha", "beta", "candidate", "final") features = __future__.all_feature_names # Verify that all_feature_names appears correct. given_feature_names = features[:] for name in dir(__future__): obj = getattr(__future__, name, None) if obj is not None and isinstance(obj, __future__._Feature): verify(name in given_feature_names, "%r should have been in all_feature_names" % name) given_feature_names.remove(name) verify( len(given_feature_names) == 0, "all_feature_names has too much: %r" % given_feature_names) del given_feature_names for feature in features: value = getattr(__future__, feature) if verbose: print "Checking __future__ ", feature, "value", value optional = value.getOptionalRelease() mandatory = value.getMandatoryRelease() verify(type(optional) is TupleType, "optional isn't tuple") verify(len(optional) == 5, "optional isn't 5-tuple") major, minor, micro, level, serial = optional verify(type(major) is IntType, "optional major isn't int") verify(type(minor) is IntType, "optional minor isn't int") verify(type(micro) is IntType, "optional micro isn't int")
from test_support import verify, verbose
""" Test script for the Unicode implementation. Written by Bill Tutt. Modified for Python 2.0 by Fredrik Lundh ([email protected]) (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """#" from test_support import verify, verbose print 'Testing General Unicode Character Name, and case insensitivity...', # General and case insensitivity test: try: # put all \N escapes inside exec'd raw strings, to make sure this # script runs even if the compiler chokes on \N escapes exec r""" s = u"\N{LATIN CAPITAL LETTER T}" \ u"\N{LATIN SMALL LETTER H}" \ u"\N{LATIN SMALL LETTER E}" \ u"\N{SPACE}" \ u"\N{LATIN SMALL LETTER R}" \ u"\N{LATIN CAPITAL LETTER E}" \ u"\N{LATIN SMALL LETTER D}" \ u"\N{SPACE}" \ u"\N{LATIN SMALL LETTER f}" \ u"\N{LATIN CAPITAL LeTtEr o}" \ u"\N{LATIN SMaLl LETTER x}" \ u"\N{SPACE}" \ u"\N{LATIN SMALL LETTER A}" \ u"\N{LATIN SMALL LETTER T}" \ u"\N{LATIN SMALL LETTER E}" \ u"\N{SPACE}" \ u"\N{LATIN SMALL LETTER T}" \ u"\N{LATIN SMALL LETTER H}" \
# Test constructors u = UserDict() u0 = UserDict(d0) u1 = UserDict(d1) u2 = IterableUserDict(d2) uu = UserDict(u) uu0 = UserDict(u0) uu1 = UserDict(u1) uu2 = UserDict(u2) # Test __repr__ verify(str(u0) == str(d0)) verify(repr(u1) == repr(d1)) verify( ` u2 ` == ` d2 `) # Test __cmp__ and __len__ all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2] for a in all: for b in all: verify(cmp(a, b) == cmp(len(a), len(b))) # Test __getitem__ verify(u2["one"] == 1) try: u1["two"]
#!/usr/bin/jython from test_support import verbose, verify from types import TupleType, StringType, IntType import __future__ GOOD_SERIALS = ("alpha", "beta", "candidate", "final") features = __future__.all_feature_names # Verify that all_feature_names appears correct. given_feature_names = features[:] for name in dir(__future__): obj = getattr(__future__, name, None) if obj is not None and isinstance(obj, __future__._Feature): verify(name in given_feature_names, "%r should have been in all_feature_names" % name) given_feature_names.remove(name) verify( len(given_feature_names) == 0, "all_feature_names has too much: %r" % given_feature_names) del given_feature_names for feature in features: value = getattr(__future__, feature) if verbose: print "Checking __future__ ", feature, "value", value optional = value.getOptionalRelease() mandatory = value.getMandatoryRelease() verify(type(optional) is TupleType, "optional isn't tuple")
def runTests(t1, t2, t3, t4, bs=0, round=0): start = 1 + round * 6 if verbose: print '%s. Simple iteration (bs=%s)' % (start + 0, bs) fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) lines = list(fi) fi.close() verify(len(lines) == 31) verify(lines[4] == 'Line 5 of file 1\n') verify(lines[30] == 'Line 1 of file 4\n') verify(fi.lineno() == 31) verify(fi.filename() == t4) if verbose: print '%s. Status variables (bs=%s)' % (start + 1, bs) fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) s = "x" while s and s != 'Line 6 of file 2\n': s = fi.readline() verify(fi.filename() == t2) verify(fi.lineno() == 21) verify(fi.filelineno() == 6) verify(not fi.isfirstline()) verify(not fi.isstdin()) if verbose: print '%s. Nextfile (bs=%s)' % (start + 2, bs) fi.nextfile() verify(fi.readline() == 'Line 1 of file 3\n') verify(fi.lineno() == 22) fi.close() if verbose: print '%s. Stdin (bs=%s)' % (start + 3, bs) fi = FileInput(files=(t1, t2, t3, t4, '-'), bufsize=bs) savestdin = sys.stdin try: sys.stdin = StringIO("Line 1 of stdin\nLine 2 of stdin\n") lines = list(fi) verify(len(lines) == 33) verify(lines[32] == 'Line 2 of stdin\n') verify(fi.filename() == '<stdin>') fi.nextfile() finally: sys.stdin = savestdin if verbose: print '%s. Boundary conditions (bs=%s)' % (start + 4, bs) fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) verify(fi.lineno() == 0) verify(fi.filename() == None) fi.nextfile() verify(fi.lineno() == 0) verify(fi.filename() == None) if verbose: print '%s. Inplace (bs=%s)' % (start + 5, bs) savestdout = sys.stdout try: fi = FileInput(files=(t1, t2, t3, t4), inplace=1, bufsize=bs) for line in fi: line = line[:-1].upper() print line fi.close() finally: sys.stdout = savestdout fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) for line in fi: verify(line[-1] == '\n') m = pat.match(line[:-1]) verify(m != None) verify(int(m.group(1)) == fi.filelineno()) fi.close()
chars = 'abcdefghijklmnopqrstuvwxyz'\ '\337\340\341\342\343\344\345\346\347\350\351\352\353\354\355\356' \ '\357\360\361\362\363\364\365\366\370\371\372\373\374\375\376\377' \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ '\300\301\302\303\304\305\306\307\310\311\312\313\314\315\316\317' \ '\320\321\322\323\324\325\326\330\331\332\333\334\335\336' expected = 'abcdefghijklmnopqrstuvwxyz' \ '%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE' \ '%EF%F0%F1%F2%F3%F4%F5%F6%F8%F9%FA%FB%FC%FD%FE%FF' \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ '%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF' \ '%D0%D1%D2%D3%D4%D5%D6%D8%D9%DA%DB%DC%DD%DE' test = urllib.quote(chars) verify(test == expected, "urllib.quote problem 1") test2 = urllib.unquote(expected) verify(test2 == chars) in1 = "abc/def" out1_1 = "abc/def" out1_2 = "abc%2Fdef" verify(urllib.quote(in1) == out1_1, "urllib.quote problem 2") verify(urllib.quote(in1, '') == out1_2, "urllib.quote problem 3") in2 = "abc?def" out2_1 = "abc%3Fdef" out2_2 = "abc?def" verify(urllib.quote(in2) == out2_1, "urllib.quote problem 4")
#! /usr/bin/env python """Test script for the gdbm module Roger E. Masse """ import gdbm from gdbm import error from test_support import verbose, verify, TestFailed filename= '/tmp/delete_me' g = gdbm.open(filename, 'c') verify(g.keys() == []) g['a'] = 'b' g['12345678910'] = '019237410982340912840198242' a = g.keys() if verbose: print 'Test gdbm file keys: ', a g.has_key('a') g.close() try: g['a'] except error: pass else: raise TestFailed, "expected gdbm.error accessing closed database" g = gdbm.open(filename, 'r') g.close() g = gdbm.open(filename, 'w') g.close()
""" Tests for uu module. Nick Mathewson """ from test_support import verify, TestFailed, verbose, TESTFN import sys, os import uu from StringIO import StringIO teststr = "The smooth-scaled python crept over the sleeping dog\n" expected = """\ M5&AE('-M;V]T:\"US8V%L960@<'ET:&]N(&-R97!T(&]V97(@=&AE('-L965P (:6YG(&1O9PH """ encoded1 = "begin 666 t1\n" + expected + "\n \nend\n" if verbose: print '1. encode file->file' inp = StringIO(teststr) out = StringIO() uu.encode(inp, out, "t1") verify(out.getvalue() == encoded1) inp = StringIO(teststr) out = StringIO() uu.encode(inp, out, "t1", 0644) verify(out.getvalue() == "begin 644 t1\n" + expected + "\n \nend\n") if verbose: print '2. decode file->file' inp = StringIO(encoded1) out = StringIO() uu.decode(inp, out) verify(out.getvalue() == teststr) inp = StringIO("""UUencoded files may contain many lines,
# Test packages (dotted-name import) import sys, os, tempfile, traceback from os import mkdir, rmdir, extsep # Can't test if these fail del mkdir, rmdir from test_support import verify, verbose, TestFailed # Helpers to create and destroy hierarchies. def mkhier(root, descr): mkdir(root) for name, contents in descr: comps = name.split() fullname = root for c in comps: fullname = os.path.join(fullname, c) if contents is None: mkdir(fullname) else: if verbose: print "write", fullname f = open(fullname, "w") f.write(contents) if contents and contents[-1] != '\n': f.write('\n') f.close() def mkdir(x): if verbose: print "mkdir", x os.mkdir(x) def cleanout(root): names = os.listdir(root)
#! /usr/bin/env python """Test script for the dbm module Roger E. Masse """ import dbm from dbm import error from test_support import verbose, verify filename = '/tmp/delete_me' d = dbm.open(filename, 'c') verify(d.keys() == []) d['a'] = 'b' d['12345678910'] = '019237410982340912840198242' d.keys() if d.has_key('a'): if verbose: print 'Test dbm keys: ', d.keys() d.close() d = dbm.open(filename, 'r') d.close() d = dbm.open(filename, 'rw') d.close() d = dbm.open(filename, 'w') d.close() d = dbm.open(filename, 'n') d.close() try: import os if dbm.library == "ndbm": # classic dbm os.unlink(filename + '.dir')
from test_support import TestFailed, verbose, verify import struct ## import pdb import sys ISBIGENDIAN = sys.byteorder == "big" del sys verify((struct.pack('=i', 1)[0] == chr(0)) == ISBIGENDIAN, "bigendian determination appears wrong") def string_reverse(s): chars = list(s) chars.reverse() return "".join(chars) def bigendian_to_native(value): if ISBIGENDIAN: return value else: return string_reverse(value) def simple_err(func, *args): try: apply(func, args) except struct.error: pass else:
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) verify(inc(1) == 2) verify(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()
def test_lecmp(s, s2): verify(s < s2 , "comparison failed on %s < %s" % (s, s2))
# test_getopt.py # David Goodger <*****@*****.**> 2000-08-19 import getopt from getopt import GetoptError from test_support import verify, verbose def expectException(teststr, expected, failure=AssertionError): """Executes a statement passed in teststr, and raises an exception (failure) if the expected exception is *not* raised.""" try: exec teststr except expected: pass else: raise failure if verbose: print 'Running tests on getopt.short_has_arg' verify(getopt.short_has_arg('a', 'a:')) verify(not getopt.short_has_arg('a', 'a')) expectException("tmp = getopt.short_has_arg('a', 'b')", GetoptError) expectException("tmp = getopt.short_has_arg('a', '')", GetoptError) if verbose: print 'Running tests on getopt.long_has_args' has_arg, option = getopt.long_has_args('abc', ['abc=']) verify(has_arg) verify(option == 'abc') has_arg, option = getopt.long_has_args('abc', ['abc']) verify(not has_arg) verify(option == 'abc') has_arg, option = getopt.long_has_args('abc', ['abcd']) verify(not has_arg)
def case_sensitivity(): print "Testing case sensitivity..." cf = ConfigParser.ConfigParser() cf.add_section("A") cf.add_section("a") L = cf.sections() L.sort() verify(L == ["A", "a"]) cf.set("a", "B", "value") verify(cf.options("a") == ["b"]) verify(cf.get("a", "b", raw=1) == "value", "could not locate option, expecting case-insensitive option names") verify(cf.has_option("a", "b")) cf.set("A", "A-B", "A-B value") for opt in ("a-b", "A-b", "a-B", "A-B"): verify(cf.has_option("A", opt), "has_option() returned false for option which should exist") verify(cf.options("A") == ["a-b"]) verify(cf.options("a") == ["b"]) cf.remove_option("a", "B") verify(cf.options("a") == []) # SF bug #432369: cf = ConfigParser.ConfigParser() sio = StringIO.StringIO("[MySection]\nOption: first line\n\tsecond line\n") cf.readfp(sio) verify(cf.options("MySection") == ["option"]) verify(cf.get("MySection", "Option") == "first line\nsecond line") # SF bug #561822: cf = ConfigParser.ConfigParser(defaults={"key":"value"}) cf.readfp(StringIO.StringIO("[section]\nnekey=nevalue\n")) verify(cf.has_option("section", "Key"))
def run_method_tests(test): """Run all tests that exercise a method of a string object""" test('capitalize', ' hello ', ' hello ') test('capitalize', 'hello ', 'Hello ') test('capitalize', 'aaaa', 'Aaaa') test('capitalize', 'AaAa', 'Aaaa') test('count', 'aaa', 3, 'a') test('count', 'aaa', 0, 'b') test('find', 'abcdefghiabc', 0, 'abc') test('find', 'abcdefghiabc', 9, 'abc', 1) test('find', 'abcdefghiabc', -1, 'def', 4) test('rfind', 'abcdefghiabc', 9, 'abc') test('lower', 'HeLLo', 'hello') test('lower', 'hello', 'hello') test('upper', 'HeLLo', 'HELLO') test('upper', 'HELLO', 'HELLO') test('title', ' hello ', ' Hello ') test('title', 'hello ', 'Hello ') test('title', "fOrMaT thIs aS titLe String", 'Format This As Title String') test('title', "fOrMaT,thIs-aS*titLe;String", 'Format,This-As*Title;String') test('title', "getInt", 'Getint') test('expandtabs', 'abc\rab\tdef\ng\thi', 'abc\rab def\ng hi') test('expandtabs', 'abc\rab\tdef\ng\thi', 'abc\rab def\ng hi', 8) test('expandtabs', 'abc\rab\tdef\ng\thi', 'abc\rab def\ng hi', 4) test('expandtabs', 'abc\r\nab\tdef\ng\thi', 'abc\r\nab def\ng hi', 4) test('islower', 'a', 1) test('islower', 'A', 0) test('islower', '\n', 0) test('islower', 'abc', 1) test('islower', 'aBc', 0) test('islower', 'abc\n', 1) test('isupper', 'a', 0) test('isupper', 'A', 1) test('isupper', '\n', 0) test('isupper', 'ABC', 1) test('isupper', 'AbC', 0) test('isupper', 'ABC\n', 1) test('istitle', 'a', 0) test('istitle', 'A', 1) test('istitle', '\n', 0) test('istitle', 'A Titlecased Line', 1) test('istitle', 'A\nTitlecased Line', 1) test('istitle', 'A Titlecased, Line', 1) test('istitle', 'Not a capitalized String', 0) test('istitle', 'Not\ta Titlecase String', 0) test('istitle', 'Not--a Titlecase String', 0) test('isalpha', 'a', 1) test('isalpha', 'A', 1) test('isalpha', '\n', 0) test('isalpha', 'abc', 1) test('isalpha', 'aBc123', 0) test('isalpha', 'abc\n', 0) test('isalnum', 'a', 1) test('isalnum', 'A', 1) test('isalnum', '\n', 0) test('isalnum', '123abc456', 1) test('isalnum', 'a1b3c', 1) test('isalnum', 'aBc000 ', 0) test('isalnum', 'abc\n', 0) # join now works with any sequence type test('join', ' ', 'a b c d', ['a', 'b', 'c', 'd']) test('join', '', 'abcd', ('a', 'b', 'c', 'd')) test('join', ' ', 'w x y z', Sequence()) test('join', 'a', 'abc', ('abc', )) test('join', 'a', 'z', UserList(['z'])) if have_unicode: test('join', unicode('.'), unicode('a.b.c'), ['a', 'b', 'c']) test('join', '.', unicode('a.b.c'), [unicode('a'), 'b', 'c']) test('join', '.', unicode('a.b.c'), ['a', unicode('b'), 'c']) test('join', '.', unicode('a.b.c'), ['a', 'b', unicode('c')]) test('join', '.', TypeError, ['a', unicode('b'), 3]) for i in [5, 25, 125]: test('join', '-', ((('a' * i) + '-') * i)[:-1], ['a' * i] * i) test('join', ' ', TypeError, BadSeq1()) test('join', ' ', 'a b c', BadSeq2()) test('splitlines', "abc\ndef\n\rghi", ['abc', 'def', '', 'ghi']) test('splitlines', "abc\ndef\n\r\nghi", ['abc', 'def', '', 'ghi']) test('splitlines', "abc\ndef\r\nghi", ['abc', 'def', 'ghi']) test('splitlines', "abc\ndef\r\nghi\n", ['abc', 'def', 'ghi']) test('splitlines', "abc\ndef\r\nghi\n\r", ['abc', 'def', 'ghi', '']) test('splitlines', "\nabc\ndef\r\nghi\n\r", ['', 'abc', 'def', 'ghi', '']) test('splitlines', "\nabc\ndef\r\nghi\n\r", ['\n', 'abc\n', 'def\r\n', 'ghi\n', '\r'], 1) test('split', 'this is the split function', ['this', 'is', 'the', 'split', 'function']) test('split', 'a|b|c|d', ['a', 'b', 'c', 'd'], '|') test('split', 'a|b|c|d', ['a', 'b', 'c|d'], '|', 2) test('split', 'a b c d', ['a', 'b c d'], None, 1) test('split', 'a b c d', ['a', 'b', 'c d'], None, 2) test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 3) test('split', 'a b c d', ['a', 'b', 'c', 'd'], None, 4) test('split', 'a b c d', ['a b c d'], None, 0) test('split', 'a b c d', ['a', 'b', 'c d'], None, 2) test('split', 'a b c d ', ['a', 'b', 'c', 'd']) test('strip', ' hello ', 'hello') test('lstrip', ' hello ', 'hello ') test('rstrip', ' hello ', ' hello') test('strip', 'hello', 'hello') test('swapcase', 'HeLLo cOmpUteRs', 'hEllO CoMPuTErS') test('translate', 'xyzabcdef', 'xyzxyz', transtable, 'def') table = string.maketrans('a', 'A') test('translate', 'abc', 'Abc', table) test('translate', 'xyz', 'xyz', table) test('replace', 'one!two!three!', 'one@two!three!', '!', '@', 1) test('replace', 'one!two!three!', 'onetwothree', '!', '') test('replace', 'one!two!three!', 'one@two@three!', '!', '@', 2) test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 3) test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 4) test('replace', 'one!two!three!', 'one!two!three!', '!', '@', 0) test('replace', 'one!two!three!', 'one@two@three@', '!', '@') test('replace', 'one!two!three!', 'one!two!three!', 'x', '@') test('replace', 'one!two!three!', 'one!two!three!', 'x', '@', 2) # Next three for SF bug 422088: [OSF1 alpha] string.replace(); died with # MemoryError due to empty result (platform malloc issue when requesting # 0 bytes). test('replace', '123', '', '123', '') test('replace', '123123', '', '123', '') test('replace', '123x123', 'x', '123', '') test('startswith', 'hello', 1, 'he') test('startswith', 'hello', 1, 'hello') test('startswith', 'hello', 0, 'hello world') test('startswith', 'hello', 1, '') test('startswith', 'hello', 0, 'ello') test('startswith', 'hello', 1, 'ello', 1) test('startswith', 'hello', 1, 'o', 4) test('startswith', 'hello', 0, 'o', 5) test('startswith', 'hello', 1, '', 5) test('startswith', 'hello', 0, 'lo', 6) test('startswith', 'helloworld', 1, 'lowo', 3) test('startswith', 'helloworld', 1, 'lowo', 3, 7) test('startswith', 'helloworld', 0, 'lowo', 3, 6) test('endswith', 'hello', 1, 'lo') test('endswith', 'hello', 0, 'he') test('endswith', 'hello', 1, '') test('endswith', 'hello', 0, 'hello world') test('endswith', 'helloworld', 0, 'worl') test('endswith', 'helloworld', 1, 'worl', 3, 9) test('endswith', 'helloworld', 1, 'world', 3, 12) test('endswith', 'helloworld', 1, 'lowo', 1, 7) test('endswith', 'helloworld', 1, 'lowo', 2, 7) test('endswith', 'helloworld', 1, 'lowo', 3, 7) test('endswith', 'helloworld', 0, 'lowo', 4, 7) test('endswith', 'helloworld', 0, 'lowo', 3, 8) test('endswith', 'ab', 0, 'ab', 0, 1) test('endswith', 'ab', 0, 'ab', 0, 0) # Encoding/decoding codecs = [('rot13', 'uryyb jbeyq'), ('base64', 'aGVsbG8gd29ybGQ=\n'), ('hex', '68656c6c6f20776f726c64'), ('uu', 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n')] for encoding, data in codecs: test('encode', 'hello world', data, encoding) test('decode', data, 'hello world', encoding) # zlib is optional, so we make the test optional too... try: import zlib except ImportError: pass else: data = 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]' verify('hello world'.encode('zlib') == data) verify(data.decode('zlib') == 'hello world')
def FailingQueueTest(q): if not q.empty(): raise RuntimeError, "Call this function with an empty queue" for i in range(queue_size-1): q.put(i) q.fail_next_put = True # Test a failing non-blocking put. try: q.put("oops", block=0) raise TestFailed("The queue didn't fail when it should have") except FailingQueueException: pass q.put("last") verify(q.full(), "Queue should be full") q.fail_next_put = True # Test a failing blocking put try: _doBlockingTest( q.put, ("full",), q.get, ()) raise TestFailed("The queue didn't fail when it should have") except FailingQueueException: pass # Check the Queue isn't damaged. # put failed, but get succeeded - re-add q.put("last") verify(q.full(), "Queue should be full") q.get() verify(not q.full(), "Queue should not be full") q.put("last") verify(q.full(), "Queue should be full") # Test a blocking put _doBlockingTest( q.put, ("full",), q.get, ()) # Empty it for i in range(queue_size): q.get() verify(q.empty(), "Queue should be empty") q.put("first") q.fail_next_get = True try: q.get() raise TestFailed("The queue didn't fail when it should have") except FailingQueueException: pass verify(not q.empty(), "Queue should not be empty") q.get() verify(q.empty(), "Queue should be empty") q.fail_next_get = True try: _doBlockingTest( q.get, (), q.put, ('empty',)) raise TestFailed("The queue didn't fail when it should have") except FailingQueueException: pass # put succeeded, but get failed. verify(not q.empty(), "Queue should not be empty") q.get() verify(q.empty(), "Queue should be empty")
def ReadTestData(root_key): # Check we can get default value for this key. val = QueryValue(root_key, test_key_name) verify(val=="Default value", "Registry didn't give back the correct value") key = OpenKey(root_key, test_key_name) # Read the sub-keys sub_key = OpenKey(key, "sub_key") # Check I can enumerate over the values. index = 0 while 1: try: data = EnumValue(sub_key, index) except EnvironmentError: break verify(data in test_data, "Didn't read back the correct test data") index = index + 1 verify(index==len(test_data), "Didn't read the correct number of items") # Check I can directly access each item for value_name, value_data, value_type in test_data: read_val, read_typ = QueryValueEx(sub_key, value_name) verify(read_val==value_data and read_typ == value_type, \ "Could not directly read the value" ) sub_key.Close() # Enumerate our main key. read_val = EnumKey(key, 0) verify(read_val == "sub_key", "Read subkey value wrong") try: EnumKey(key, 1) verify(0, "Was able to get a second key when I only have one!") except EnvironmentError: pass key.Close()
def test_one(self, x, pack=struct.pack, unpack=struct.unpack, unhexlify=binascii.unhexlify): if verbose: print "trying std", self.formatpair, "on", x, "==", hex(x) # Try signed. code = self.signed_code if self.signed_min <= x <= self.signed_max: # Try big-endian. expected = long(x) if x < 0: expected += 1L << self.bitsize assert expected > 0 expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (self.bytesize - len(expected)) + expected # Pack work? format = ">" + code got = pack(format, x) verify( got == expected, "'%s'-pack of %r gave %r, not %r" % (format, x, got, expected)) # Unpack work? retrieved = unpack(format, got)[0] verify( x == retrieved, "'%s'-unpack of %r gave %r, not %r" % (format, got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, format, '\x01' + got) # Try little-endian. format = "<" + code expected = string_reverse(expected) # Pack work? got = pack(format, x) verify( got == expected, "'%s'-pack of %r gave %r, not %r" % (format, x, got, expected)) # Unpack work? retrieved = unpack(format, got)[0] verify( x == retrieved, "'%s'-unpack of %r gave %r, not %r" % (format, got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, format, '\x01' + got) else: # x is out of range -- verify pack realizes that. if code in self.BUGGY_RANGE_CHECK: if verbose: print "Skipping buggy range check for code", code else: any_err(pack, ">" + code, x) any_err(pack, "<" + code, x) # Much the same for unsigned. code = self.unsigned_code if self.unsigned_min <= x <= self.unsigned_max: # Try big-endian. format = ">" + code expected = long(x) expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) expected = "\x00" * (self.bytesize - len(expected)) + expected # Pack work? got = pack(format, x) verify( got == expected, "'%s'-pack of %r gave %r, not %r" % (format, x, got, expected)) # Unpack work? retrieved = unpack(format, got)[0] verify( x == retrieved, "'%s'-unpack of %r gave %r, not %r" % (format, got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, format, '\x01' + got) # Try little-endian. format = "<" + code expected = string_reverse(expected) # Pack work? got = pack(format, x) verify( got == expected, "'%s'-pack of %r gave %r, not %r" % (format, x, got, expected)) # Unpack work? retrieved = unpack(format, got)[0] verify( x == retrieved, "'%s'-unpack of %r gave %r, not %r" % (format, got, retrieved, x)) # Adding any byte should cause a "too big" error. any_err(unpack, format, '\x01' + got) else: # x is out of range -- verify pack realizes that. if code in self.BUGGY_RANGE_CHECK: if verbose: print "Skipping buggy range check for code", code else: any_err(pack, ">" + code, x) any_err(pack, "<" + code, x)
return self def next(self): if self.c == 4: raise StopIteration c = self.c self.c += 1 return c g(*Nothing()) # make sure the function call doesn't stomp on the dictionary? d = {'a': 1, 'b': 2, 'c': 3} d2 = d.copy() verify(d == d2) g(1, d=4, **d) print sortdict(d) print sortdict(d2) verify(d == d2, "function call modified dictionary") # what about willful misconduct? def saboteur(**kw): kw['x'] = locals() # yields a cyclic kw return kw d = {} kw = saboteur(a=1, **d) verify(d == {})
def basic(src): print "Testing basic accessors..." cf = ConfigParser.ConfigParser() sio = StringIO.StringIO(src) cf.readfp(sio) L = cf.sections() L.sort() verify(L == [r'Commented Bar', r'Foo Bar', r'Internationalized Stuff', r'Long Line', r'Section\with$weird%characters[' '\t', r'Spaces', r'Spacey Bar', ], "unexpected list of section names") # The use of spaces in the section names serves as a regression test for # SourceForge bug #115357. # http://sourceforge.net/bugs/?func=detailbug&group_id=5470&bug_id=115357 verify(cf.get('Foo Bar', 'foo', raw=1) == 'bar') verify(cf.get('Spacey Bar', 'foo', raw=1) == 'bar') verify(cf.get('Commented Bar', 'foo', raw=1) == 'bar') verify(cf.get('Spaces', 'key with spaces', raw=1) == 'value') verify(cf.get('Spaces', 'another with spaces', raw=1) == 'splat!') verify('__name__' not in cf.options("Foo Bar"), '__name__ "option" should not be exposed by the API!') # Make sure the right things happen for remove_option(); # added to include check for SourceForge bug #123324: verify(cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report existance of option") verify(not cf.has_option('Foo Bar', 'foo'), "remove_option() failed to remove option") verify(not cf.remove_option('Foo Bar', 'foo'), "remove_option() failed to report non-existance of option" " that was removed") try: cf.remove_option('No Such Section', 'foo') except ConfigParser.NoSectionError: pass else: raise TestFailed( "remove_option() failed to report non-existance of option" " that never existed") verify(cf.get('Long Line', 'foo', raw=1) == 'this line is much, much longer than my editor\nlikes it.')
def test_func_doc(): def f(): pass verify(f.__doc__ is None) verify(f.func_doc is None) f.__doc__ = "hello" verify(f.__doc__ == "hello") verify(f.func_doc == "hello") del f.__doc__ verify(f.__doc__ is None) verify(f.func_doc is None) f.func_doc = "world" verify(f.__doc__ == "world") verify(f.func_doc == "world") del f.func_doc verify(f.func_doc is None) verify(f.__doc__ is None)
def test_func_globals(): def f(): pass verify(f.func_globals is globals()) cantset(f, "func_globals", globals())
""" Test script for the Unicode implementation. Written by Marc-Andre Lemburg ([email protected]). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """#" from test_support import verify, verbose, TestFailed import sys, string if not sys.platform.startswith('java'): # Test basic sanity of repr() verify(repr(u'abc') == "u'abc'") verify(repr(u'ab\\c') == "u'ab\\\\c'") verify(repr(u'ab\\') == "u'ab\\\\'") verify(repr(u'\\c') == "u'\\\\c'") verify(repr(u'\\') == "u'\\\\'") verify(repr(u'\n') == "u'\\n'") verify(repr(u'\r') == "u'\\r'") verify(repr(u'\t') == "u'\\t'") verify(repr(u'\b') == "u'\\x08'") verify(repr(u"'\"") == """u'\\'"'""") verify(repr(u"'\"") == """u'\\'"'""") verify(repr(u"'") == '''u"'"''') verify(repr(u'"') == """u'"'""") verify(repr(u''.join(map(unichr, range(256)))) == "u'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r" "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a" "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI" "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f" "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
def test_func_dict(): def f(): pass a = f.__dict__ b = f.func_dict verify(a == {}) verify(a is b) f.hello = 'world' verify(a == {'hello': 'world'}) verify(f.func_dict is a is f.__dict__) f.func_dict = {} verify(not hasattr(f, "hello")) f.__dict__ = {'world': 'hello'} verify(f.world == "hello") verify(f.__dict__ is f.func_dict == {'world': 'hello'}) cantset(f, "func_dict", None) cantset(f, "__dict__", None)
"""This test checks for correct fork() behavior.
import os from test_support import verify, TESTFN from UserList import UserList # verify writelines with instance sequence l = UserList(['1', '2']) f = open(TESTFN, 'wb') f.writelines(l) f.close() f = open(TESTFN, 'rb') buf = f.read() f.close() verify(buf == '12') # verify writelines with integers f = open(TESTFN, 'wb') try: f.writelines([1, 2, 3]) except TypeError: pass else: print "writelines accepted sequence of integers" f.close() # verify writelines with integers in UserList f = open(TESTFN, 'wb') l = UserList([1,2,3]) try: f.writelines(l) except TypeError:
""" data2 = """/* zlibmodule.c -- gzip-compatible data compression */ /* See http://www.cdrom.com/pub/infozip/zlib/ */ /* See http://www.winimage.com/zLibDll for Windows */ """ f = gzip.GzipFile(filename, 'wb') f.write(data1 * 50) f.close() f = gzip.GzipFile(filename, 'r') d = f.read() f.close() verify(d == data1 * 50) # Append to the previous file f = gzip.GzipFile(filename, 'ab') f.write(data2 * 15) f.close() f = gzip.GzipFile(filename, 'rb') d = f.read() f.close() verify(d == (data1 * 50) + (data2 * 15)) # Try .readline() with varying line lengths f = gzip.GzipFile(filename, 'rb') line_length = 0
writeFiles() runTests(t1, t2, t3, t4, bs, round) finally: remove_tempfiles(t1, t2, t3, t4) # Next, check for proper behavior with 0-byte files. if verbose: print "13. 0-byte files" try: t1 = writeTmp(1, [""]) t2 = writeTmp(2, [""]) t3 = writeTmp(3, ["The only line there is.\n"]) t4 = writeTmp(4, [""]) fi = FileInput(files=(t1, t2, t3, t4)) line = fi.readline() verify(line == 'The only line there is.\n') verify(fi.lineno() == 1) verify(fi.filelineno() == 1) verify(fi.filename() == t3) line = fi.readline() verify(not line) verify(fi.lineno() == 1) verify(fi.filelineno() == 0) verify(fi.filename() == t4) fi.close() finally: remove_tempfiles(t1, t2, t3, t4) if verbose: print "14. Files that don't end with newline" try: