rem
stringlengths
1
322k
add
stringlengths
0
2.05M
context
stringlengths
4
228k
meta
stringlengths
156
215
<SCRIPT LANGUAGE="JavaScript">
<script type="text/javascript">
def js_output(self, attrs=None): # Print javascript return """ <SCRIPT LANGUAGE="JavaScript"> <!-- begin hiding document.cookie = \"%s\" // end hiding --> </script> """ % ( self.OutputString(attrs), )
03a33ea3a85f9f2ed158f678295b7605f2f9721a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/03a33ea3a85f9f2ed158f678295b7605f2f9721a/Cookie.py
document.cookie = \"%s\"
document.cookie = \"%s\";
def js_output(self, attrs=None): # Print javascript return """ <SCRIPT LANGUAGE="JavaScript"> <!-- begin hiding document.cookie = \"%s\" // end hiding --> </script> """ % ( self.OutputString(attrs), )
03a33ea3a85f9f2ed158f678295b7605f2f9721a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/03a33ea3a85f9f2ed158f678295b7605f2f9721a/Cookie.py
def writelines(self, list): self.write(''.join(list))
def writelines(self, iterable): write = self.write for line in iterable: write(line)
def writelines(self, list): self.write(''.join(list))
6ec099658ab49ed6d3c2861e437fe659e1c7037f /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/6ec099658ab49ed6d3c2861e437fe659e1c7037f/StringIO.py
prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1] != item[:i+1]: prefix = prefix[:i] if i == 0: return '' break return prefix
s1 = min(m) s2 = max(m) n = min(len(s1), len(s2)) for i in xrange(n): if s1[i] != s2[i]: return s1[:i] return s1[:n]
def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1] != item[:i+1]: prefix = prefix[:i] if i == 0: return '' break return prefix
74bb7f03b1ff097d2e08544539549ec7283ffc75 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/74bb7f03b1ff097d2e08544539549ec7283ffc75/posixpath.py
def start_doctype_decl(self, name, pubid, sysid, has_internal_subset):
def start_doctype_decl(self, name, sysid, pubid, has_internal_subset):
def start_doctype_decl(self, name, pubid, sysid, has_internal_subset): self._lex_handler_prop.startDTD(name, pubid, sysid)
456ab1d2712dc9cebd878966c8fb16af47ea79f0 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/456ab1d2712dc9cebd878966c8fb16af47ea79f0/expatreader.py
if mname in self.modules: return self.modules[mname] self.modules[mname] = m = self.hooks.new_module(mname)
m = self.modules.get(mname) if m is None: self.modules[mname] = m = self.hooks.new_module(mname)
def add_module(self, mname): if mname in self.modules: return self.modules[mname] self.modules[mname] = m = self.hooks.new_module(mname) m.__builtins__ = self.modules['__builtin__'] return m
7f7c3d0a9c401d7bc9a9d86ec7181cf09c4b3bab /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/7f7c3d0a9c401d7bc9a9d86ec7181cf09c4b3bab/rexec.py
code.interact( "*** RESTRICTED *** Python %s on %s\n" 'Type "help", "copyright", "credits" or "license" ' "for more information." % (sys.version, sys.platform), local=r.modules['__main__'].__dict__)
RestrictedConsole(r.modules['__main__'].__dict__).interact()
def test(): import getopt, traceback opts, args = getopt.getopt(sys.argv[1:], 'vt:') verbose = 0 trusted = [] for o, a in opts: if o == '-v': verbose = verbose+1 if o == '-t': trusted.append(a) r = RExec(verbose=verbose) if trusted: r.ok_builtin_modules = r.ok_builtin_modules + tuple(trusted) if args: r.modules['sys'].argv = args r.modules['sys'].path.insert(0, os.path.dirname(args[0])) else: r.modules['sys'].path.insert(0, "") fp = sys.stdin if args and args[0] != '-': try: fp = open(args[0]) except IOError, msg: print "%s: can't open file %s" % (sys.argv[0], `args[0]`) return 1 if fp.isatty(): import code try: code.interact( "*** RESTRICTED *** Python %s on %s\n" 'Type "help", "copyright", "credits" or "license" ' "for more information." % (sys.version, sys.platform), local=r.modules['__main__'].__dict__) except SystemExit, n: return n else: text = fp.read() fp.close() c = compile(text, fp.name, 'exec') try: r.s_exec(c) except SystemExit, n: return n except: traceback.print_exc() return 1
7f7c3d0a9c401d7bc9a9d86ec7181cf09c4b3bab /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/7f7c3d0a9c401d7bc9a9d86ec7181cf09c4b3bab/rexec.py
if w[0] != '-' and w[-2:] in ('.o', '.a'):
if w[0] not in ('-', '$') and w[-2:] in ('.o', '.a'):
def select(e, mods, vars, mod, skipofiles): files = [] for w in mods[mod]: w = treatword(w) if not w: continue w = expandvars(w, vars) for w in string.split(w): if skipofiles and w[-2:] == '.o': continue if w[0] != '-' and w[-2:] in ('.o', '.a'): w = os.path.join(e, w) if w[:2] in ('-L', '-R'): w = w[:2] + os.path.join(e, w[2:]) files.append(w) return files
ce7695191fdcfd5564a6fdf7f54255c74206a8c2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/ce7695191fdcfd5564a6fdf7f54255c74206a8c2/checkextensions.py
if w[:2] in ('-L', '-R'):
if w[:2] in ('-L', '-R') and w[2:3] != '$':
def select(e, mods, vars, mod, skipofiles): files = [] for w in mods[mod]: w = treatword(w) if not w: continue w = expandvars(w, vars) for w in string.split(w): if skipofiles and w[-2:] == '.o': continue if w[0] != '-' and w[-2:] in ('.o', '.a'): w = os.path.join(e, w) if w[:2] in ('-L', '-R'): w = w[:2] + os.path.join(e, w[2:]) files.append(w) return files
ce7695191fdcfd5564a6fdf7f54255c74206a8c2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/ce7695191fdcfd5564a6fdf7f54255c74206a8c2/checkextensions.py
dstfinfo = dstfss.GetFInfo() dstfinfo.Flags = dstfinfo.Flags|0x8000 dstfss.SetFInfo(dstfinfo) def main(): dir, ok = macfs.GetDirectory() if not ok: sys.exit(0) os.chdir(dir.as_pathname())
if __name__ == '__main__': run(1)
def mkalias(src, dst): """Create a finder alias""" srcfss = macfs.FSSpec(src) dstfss = macfs.FSSpec(dst) alias = srcfss.NewAlias() srcfinfo = srcfss.GetFInfo() Res.FSpCreateResFile(dstfss, srcfinfo.Creator, srcfinfo.Type, -1) h = Res.FSpOpenResFile(dstfss, 3) resource = Res.Resource(alias.data) resource.AddResource('alis', 0, '') Res.CloseResFile(h) dstfinfo = dstfss.GetFInfo() dstfinfo.Flags = dstfinfo.Flags|0x8000 # Alias flag dstfss.SetFInfo(dstfinfo)
d8eb8a79456555385185782df350c39233104341 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/d8eb8a79456555385185782df350c39233104341/fixfiletypes.py
if EasyDialogs.AskYesNoCancel('Proceed with removing old aliases?') <= 0: sys.exit(0) LibFiles = [] allfiles = os.listdir(':') for f in allfiles: if f[-4:] == '.slb': finfo = macfs.FSSpec(f).GetFInfo() if finfo.Flags & 0x8000: os.unlink(f) else: LibFiles.append(f)
def main(): # Ask the user for the plugins directory dir, ok = macfs.GetDirectory() if not ok: sys.exit(0) os.chdir(dir.as_pathname()) # Remove old .slb aliases and collect a list of .slb files if EasyDialogs.AskYesNoCancel('Proceed with removing old aliases?') <= 0: sys.exit(0) LibFiles = [] allfiles = os.listdir(':') for f in allfiles: if f[-4:] == '.slb': finfo = macfs.FSSpec(f).GetFInfo() if finfo.Flags & 0x8000: os.unlink(f) else: LibFiles.append(f) print LibFiles # Create the new aliases. if EasyDialogs.AskYesNoCancel('Proceed with creating new ones?') <= 0: sys.exit(0) for dst, src in goals: if src in LibFiles: mkalias(src, dst) else: EasyDialogs.Message(dst+' not created: '+src+' not found') EasyDialogs.Message('All done!')
d8eb8a79456555385185782df350c39233104341 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/d8eb8a79456555385185782df350c39233104341/fixfiletypes.py
print LibFiles if EasyDialogs.AskYesNoCancel('Proceed with creating new ones?') <= 0: sys.exit(0) for dst, src in goals: if src in LibFiles: mkalias(src, dst) else: EasyDialogs.Message(dst+' not created: '+src+' not found') EasyDialogs.Message('All done!') if __name__ == '__main__': main()
def main(): # Ask the user for the plugins directory dir, ok = macfs.GetDirectory() if not ok: sys.exit(0) os.chdir(dir.as_pathname()) # Remove old .slb aliases and collect a list of .slb files if EasyDialogs.AskYesNoCancel('Proceed with removing old aliases?') <= 0: sys.exit(0) LibFiles = [] allfiles = os.listdir(':') for f in allfiles: if f[-4:] == '.slb': finfo = macfs.FSSpec(f).GetFInfo() if finfo.Flags & 0x8000: os.unlink(f) else: LibFiles.append(f) print LibFiles # Create the new aliases. if EasyDialogs.AskYesNoCancel('Proceed with creating new ones?') <= 0: sys.exit(0) for dst, src in goals: if src in LibFiles: mkalias(src, dst) else: EasyDialogs.Message(dst+' not created: '+src+' not found') EasyDialogs.Message('All done!')
d8eb8a79456555385185782df350c39233104341 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/d8eb8a79456555385185782df350c39233104341/fixfiletypes.py
- prepend _ if the result is a python keyword
- append _ if the result is a python keyword
def identify(str): """Turn any string into an identifier: - replace space by _ - replace other illegal chars by _xx_ (hex code) - prepend _ if the result is a python keyword """ if not str: return "empty_ae_name_" rv = '' ok = string.ascii_letters + '_' ok2 = ok + string.digits for c in str: if c in ok: rv = rv + c elif c == ' ': rv = rv + '_' else: rv = rv + '_%02.2x_'%ord(c) ok = ok2 if keyword.iskeyword(rv): rv = rv + '_' return rv
36d49a907fdc1dd34ee30b3b407ea9d92e35f4f9 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36d49a907fdc1dd34ee30b3b407ea9d92e35f4f9/gensuitemodule.py
import _socket
if not sys.platform.startswith('java'): import _socket
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))
cbfc0343fc66cb4bd7f962698c81ff74b94ea554 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/cbfc0343fc66cb4bd7f962698c81ff74b94ea554/test___all__.py
finfo = macfs.FSSpec(name).GetFInfo()
finfo = FSSpec(name).FSpGetFInfo()
def getfileinfo(name): finfo = macfs.FSSpec(name).GetFInfo() dir, file = os.path.split(name) # XXXX Get resource/data sizes fp = open(name, 'rb') fp.seek(0, 2) dlen = fp.tell() fp = openrf(name, '*rb') fp.seek(0, 2) rlen = fp.tell() return file, finfo, dlen, rlen
5ea4bf1c58aee31ed15faad6985d9a36498fdf02 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/5ea4bf1c58aee31ed15faad6985d9a36498fdf02/binhex.py
def getfileinfo(name): finfo = macfs.FSSpec(name).GetFInfo() dir, file = os.path.split(name) # XXXX Get resource/data sizes fp = open(name, 'rb') fp.seek(0, 2) dlen = fp.tell() fp = openrf(name, '*rb') fp.seek(0, 2) rlen = fp.tell() return file, finfo, dlen, rlen
5ea4bf1c58aee31ed15faad6985d9a36498fdf02 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/5ea4bf1c58aee31ed15faad6985d9a36498fdf02/binhex.py
else:
except ImportError:
def openrsrc(name, *mode): if not mode: mode = '*rb' else: mode = '*' + mode[0] return openrf(name, mode)
5ea4bf1c58aee31ed15faad6985d9a36498fdf02 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/5ea4bf1c58aee31ed15faad6985d9a36498fdf02/binhex.py
fss = macfs.FSSpec(ofname)
fss = FSSpec(ofname)
def __init__(self, (name, finfo, dlen, rlen), ofp): if type(ofp) == type(''): ofname = ofp ofp = open(ofname, 'w') if os.name == 'mac': fss = macfs.FSSpec(ofname) fss.SetCreatorType('BnHq', 'TEXT') ofp.write('(This file must be converted with BinHex 4.0)\n\n:') hqxer = _Hqxcoderengine(ofp) self.ofp = _Rlecoderengine(hqxer) self.crc = 0 if finfo is None: finfo = FInfo() self.dlen = dlen self.rlen = rlen self._writeinfo(name, finfo) self.state = _DID_HEADER
5ea4bf1c58aee31ed15faad6985d9a36498fdf02 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/5ea4bf1c58aee31ed15faad6985d9a36498fdf02/binhex.py
ofss = macfs.FSSpec(out)
ofss = FSSpec(out)
def hexbin(inp, out): """(infilename, outfilename) - Decode binhexed file""" ifp = HexBin(inp) finfo = ifp.FInfo if not out: out = ifp.FName if os.name == 'mac': ofss = macfs.FSSpec(out) out = ofss.as_pathname() ofp = open(out, 'wb') # XXXX Do translation on non-mac systems while 1: d = ifp.read(128000) if not d: break ofp.write(d) ofp.close() ifp.close_data() d = ifp.read_rsrc(128000) if d: ofp = openrsrc(out, 'wb') ofp.write(d) while 1: d = ifp.read_rsrc(128000) if not d: break ofp.write(d) ofp.close() if os.name == 'mac': nfinfo = ofss.GetFInfo() nfinfo.Creator = finfo.Creator nfinfo.Type = finfo.Type nfinfo.Flags = finfo.Flags ofss.SetFInfo(nfinfo) ifp.close()
5ea4bf1c58aee31ed15faad6985d9a36498fdf02 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/5ea4bf1c58aee31ed15faad6985d9a36498fdf02/binhex.py
prog = open(filename).read()
prog = open(filename, "rU").read()
def find_executable_linenos(filename): """Return dict where keys are line numbers in the line number table.""" assert filename.endswith('.py') try: prog = open(filename).read() except IOError, err: print >> sys.stderr, ("Not printing coverage data for %r: %s" % (filename, err)) return {} code = compile(prog, filename, "exec") strs = find_strings(filename) return find_lines(code, strs)
c00fc8452e1ce89ede278f417a2bd272bda98eae /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/c00fc8452e1ce89ede278f417a2bd272bda98eae/trace.py
print `header`
def decode(input, output, resonly=0): if type(input) == type(''): input = open(input, 'rb') # Should we also test for FSSpecs or FSRefs? header = input.read(AS_HEADER_LENGTH) print `header` try: magic, version, dummy, nentry = struct.unpack(AS_HEADER_FORMAT, header) except ValueError, arg: raise Error, "Unpack header error: %s"%arg if verbose: print 'Magic: 0x%8.8x'%magic print 'Version: 0x%8.8x'%version print 'Entries: %d'%nentry if magic != AS_MAGIC: raise Error, 'Unknown AppleSingle magic number 0x%8.8x'%magic if version != AS_VERSION: raise Error, 'Unknown AppleSingle version number 0x%8.8x'%version if nentry <= 0: raise Error, "AppleSingle file contains no forks" headers = [input.read(AS_ENTRY_LENGTH) for i in range(nentry)] didwork = 0 for hdr in headers: try: id, offset, length = struct.unpack(AS_ENTRY_FORMAT, hdr) except ValueError, arg: raise Error, "Unpack entry error: %s"%arg if verbose: print 'Fork %d, offset %d, length %d'%(id, offset, length) input.seek(offset) if length == 0: data = '' else: data = input.read(length) if len(data) != length: raise Error, 'Short read: expected %d bytes got %d'%(length, len(data)) if id == AS_DATAFORK: if verbose: print ' (data fork)' if not resonly: didwork = 1 fp = open(output, 'wb') fp.write(data) fp.close() elif id == AS_RESOURCEFORK: didwork = 1 if verbose: print ' (resource fork)' if resonly: fp = open(output, 'wb') else: fp = MacOS.openrf(output, 'wb') fp.write(data) fp.close() elif id in AS_IGNORE: if verbose: print ' (ignored)' else: raise Error, 'Unknown fork type %d'%id if not didwork: raise Error, 'No useful forks found'
695b33b02a0288819c2b0e61f5b1e28bcd5ac966 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/695b33b02a0288819c2b0e61f5b1e28bcd5ac966/applesingle.py
def set_get_returns_none(self, *args, **kwargs): return apply(self._cobj.set_get_returns_none, args, kwargs)
def set_get_returns_none(self, *args, **kwargs): return apply(self._cobj.set_get_returns_none, args, kwargs)
db8a80735b9ce54f26d3e6796d0ae647455ca854 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/db8a80735b9ce54f26d3e6796d0ae647455ca854/dbobj.py
if not debugger:
if not debugger and \ self.editwin.getvar("<<toggle-jit-stack-viewer>>"):
def run_module_event(self, event, debugger=None): if not self.editwin.get_saved(): tkMessageBox.showerror("Not saved", "Please save first!", master=self.editwin.text) self.editwin.text.focus_set() return filename = self.editwin.io.filename if not filename: tkMessageBox.showerror("No file name", "This window has no file name", master=self.editwin.text) self.editwin.text.focus_set() return modname, ext = os.path.splitext(os.path.basename(filename)) if sys.modules.has_key(modname): mod = sys.modules[modname] else: mod = imp.new_module(modname) sys.modules[modname] = mod mod.__file__ = filename saveout = sys.stdout saveerr = sys.stderr owin = OnDemandOutputWindow(self.editwin.flist) try: sys.stderr = PseudoFile(owin, "stderr") try: sys.stdout = PseudoFile(owin, "stdout") try: if debugger: debugger.run("execfile(%s)" % `filename`, mod.__dict__) else: execfile(filename, mod.__dict__) except: (sys.last_type, sys.last_value, sys.last_traceback) = sys.exc_info() linecache.checkcache() traceback.print_exc() if not debugger: from StackViewer import StackBrowser sv = StackBrowser(self.root, self.flist) finally: sys.stdout = saveout finally: sys.stderr = saveerr
9ea32898dbfe88426f031d60126e44d5279e2ded /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/9ea32898dbfe88426f031d60126e44d5279e2ded/ScriptBinding.py
manifest = open (self.manifest, "w") for fn in self.files: manifest.write (fn + '\n') manifest.close ()
self.execute(write_file, (self.manifest, self.files), "writing manifest file")
def write_manifest (self): """Write the file list in 'self.files' (presumably as filled in by 'find_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'."""
1b8e1d4c0dd1a1d738ffdac053446117f6d70656 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/1b8e1d4c0dd1a1d738ffdac053446117f6d70656/sdist.py
['response', ['mesg_num octets', ...]].
['response', ['mesg_num octets', ...], octets].
def list(self, which=None): """Request listing, return result.
2772c679e9c9503965301541ffa2a730c2527976 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/2772c679e9c9503965301541ffa2a730c2527976/poplib.py
except:
except IOError:
def is_zipfile(filename): """Quickly see if file is a ZIP file by checking the magic number. Will not accept a ZIP archive with an ending comment. """ try: fpin = open(filename, "rb") fpin.seek(-22, 2) # Seek to end-of-file record endrec = fpin.read() fpin.close() if endrec[0:4] == "PK\005\006" and endrec[-2:] == "\000\000": return 1 # file has correct magic number except: pass
7e473800c31e650ad573e5af21a6ed63e155c2f6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/7e473800c31e650ad573e5af21a6ed63e155c2f6/zipfile.py
sentence_end = ".?!"
sentence_end_re = re.compile(r'[%s]' r'[\.\!\?]' r'[\"\']?' % string.lowercase)
def islower (c): return c in string.lowercase
9b4864e40af38eee803b65e9a336a1590b0f633e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/9b4864e40af38eee803b65e9a336a1590b0f633e/textwrap.py
punct = self.sentence_end
pat = self.sentence_end_re
def _fix_sentence_endings (self, chunks): """_fix_sentence_endings(chunks : [string])
9b4864e40af38eee803b65e9a336a1590b0f633e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/9b4864e40af38eee803b65e9a336a1590b0f633e/textwrap.py
if (chunks[i][-1] in punct and chunks[i+1] == " " and islower(chunks[i][-2])):
if chunks[i+1] == " " and pat.search(chunks[i]):
def _fix_sentence_endings (self, chunks): """_fix_sentence_endings(chunks : [string])
9b4864e40af38eee803b65e9a336a1590b0f633e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/9b4864e40af38eee803b65e9a336a1590b0f633e/textwrap.py
self._file.write(struct.pack('<lsslhhllhhs',
self._file.write(struct.pack('<l4s4slhhllhh4s',
def _write_header(self, initlength): self._file.write('RIFF') if not self._nframes: self._nframes = initlength / (self._nchannels * self._sampwidth) self._datalength = self._nframes * self._nchannels * self._sampwidth self._form_length_pos = self._file.tell() self._file.write(struct.pack('<lsslhhllhhs', 36 + self._datalength, 'WAVE', 'fmt ', 16, WAVE_FORMAT_PCM, self._nchannels, self._framerate, self._nchannels * self._framerate * self._sampwidth, self._nchannels * self._sampwidth, self._sampwidth * 8, 'data')) self._data_length_pos = self._file.tell() self._file.write(struct.pack('<l', self._datalength))
eca576c68be8299b006251eeea0f23068520ed57 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/eca576c68be8299b006251eeea0f23068520ed57/wave.py
print cmd
def _remote(self, action, autoraise): raise_opt = ("-noraise", "-raise")[autoraise] cmd = "%s %s -remote '%s' >/dev/null 2>&1" % (self.name, raise_opt, action) print cmd rc = os.system(cmd) if rc: import time os.system("%s &" % self.name) time.sleep(PROCESS_CREATION_DELAY) rc = os.system(cmd) return not rc
cb33165ca2f8c1493b511bb7b38b44ede4211280 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/cb33165ca2f8c1493b511bb7b38b44ede4211280/webbrowser.py
_tryorder = ("mozilla","netscape","kfm","grail","links","lynx","w3m")
_tryorder = ["mozilla","netscape","kfm","grail","links","lynx","w3m"]
def open_new(self, url): self.open(url)
cb33165ca2f8c1493b511bb7b38b44ede4211280 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/cb33165ca2f8c1493b511bb7b38b44ede4211280/webbrowser.py
_tryorder = ("netscape", "windows-default")
_tryorder = ["netscape", "windows-default"]
def open_new(self, url): self.open(url)
cb33165ca2f8c1493b511bb7b38b44ede4211280 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/cb33165ca2f8c1493b511bb7b38b44ede4211280/webbrowser.py
_tryorder = ("internet-config", )
_tryorder = ["internet-config"]
def open_new(self, url): self.open(url)
cb33165ca2f8c1493b511bb7b38b44ede4211280 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/cb33165ca2f8c1493b511bb7b38b44ede4211280/webbrowser.py
_tryorder = ("os2netscape",)
_tryorder = ["os2netscape"]
def open_new(self, url): self.open(url)
cb33165ca2f8c1493b511bb7b38b44ede4211280 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/cb33165ca2f8c1493b511bb7b38b44ede4211280/webbrowser.py
if hasattr(os, 'utime'): past = time.time() - 3 os.utime(testfile, (past, past)) else: time.sleep(3)
def test(): raise ValueError""" # if this test runs fast, test_bug737473.py will have same mtime # even if it's rewrited and it'll not reloaded. so adjust mtime # of original to past. if hasattr(os, 'utime'): past = time.time() - 3 os.utime(testfile, (past, past)) else: time.sleep(3) if 'test_bug737473' in sys.modules: del sys.modules['test_bug737473'] import test_bug737473 try: test_bug737473.test() except ValueError: # this loads source code to linecache traceback.extract_tb(sys.exc_traceback) print >> open(testfile, 'w'), """\
4a8d8519106789688d9a10a5c20e7b0d29b70024 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/4a8d8519106789688d9a10a5c20e7b0d29b70024/test_traceback.py
self.rfile.flush()
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such CGI script (%s)" % `scriptname`) return if not os.path.isfile(scriptfile): self.send_error(403, "CGI script is not a plain file (%s)" % `scriptname`) return ispy = self.is_python(scriptname) if not ispy: if not (self.have_fork or self.have_popen2 or self.have_popen3): self.send_error(403, "CGI script is not a Python script (%s)" % `scriptname`) return if not self.is_executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return
b54c27c861ad71fc090939da4c5fdb4f5e3bc67c /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/b54c27c861ad71fc090939da4c5fdb4f5e3bc67c/CGIHTTPServer.py
return From(fromname, [('*', None)])
return From(fromname, [('*', None)], lineno=nodelist[0][2])
def import_from(self, nodelist): # import_from: 'from' dotted_name 'import' ('*' | # '(' import_as_names ')' | import_as_names) assert nodelist[0][1] == 'from' assert nodelist[1][0] == symbol.dotted_name assert nodelist[2][1] == 'import' fromname = self.com_dotted_name(nodelist[1]) if nodelist[3][0] == token.STAR: # TODO(jhylton): where is the lineno? return From(fromname, [('*', None)]) else: node = nodelist[3 + (nodelist[3][0] == token.LPAR)] return From(fromname, self.com_import_as_names(node), lineno=nodelist[0][2])
05522ad795fe83dd1ffee4923c36d2ee8890708c /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/05522ad795fe83dd1ffee4923c36d2ee8890708c/transformer.py
test.test_support.run_unittest(XrangeTest)
test.test_support.run_unittest(BytesTest)
def test_main(): test.test_support.run_unittest(XrangeTest)
5f6f27de4d9f7cb260e243cf517cec629e54e985 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/5f6f27de4d9f7cb260e243cf517cec629e54e985/test_bytes.py
self.fail("Error testing host resolution mechanisms.")
self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqdn, repr(all_host_names)))
def testHostnameRes(self): # Testing hostname resolution mechanisms hostname = socket.gethostname() try: ip = socket.gethostbyname(hostname) except socket.error: # Probably name lookup wasn't set up right; skip this test return self.assert_(ip.find('.') >= 0, "Error resolving host to ip.") try: hname, aliases, ipaddrs = socket.gethostbyaddr(ip) except socket.error: # Probably a similar problem as above; skip this test return all_host_names = [hostname, hname] + aliases fqhn = socket.getfqdn() if not fqhn in all_host_names: self.fail("Error testing host resolution mechanisms.")
c667d052e5c10ef519c61fd9c2e2713cc99297a9 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/c667d052e5c10ef519c61fd9c2e2713cc99297a9/test_socket.py
interp = interp[:-5] = interp[-4:]
interp = interp[:-5] + interp[-4:]
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such CGI script (%s)" % `scriptname`) return if not os.path.isfile(scriptfile): self.send_error(403, "CGI script is not a plain file (%s)" % `scriptname`) return ispy = self.is_python(scriptname) if not ispy: if not (self.have_fork or self.have_popen2): self.send_error(403, "CGI script is not a Python script (%s)" % `scriptname`) return if not self.is_executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return
0afde13b435f484ecbc3e95107d2318415f21d29 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/0afde13b435f484ecbc3e95107d2318415f21d29/CGIHTTPServer.py
if a.index(-2,-10) != 0: raise TestFailed, 'list index, negative start argument'
if a.index(0,-4) != 2: raise TestFailed, 'list index, -start argument' if a.index(-2,-10) != 0: raise TestFailed, 'list index, very -start argument'
def __getitem__(self, key): return str(key) + '!!!'
2743d87d7934535f16a0ea062a28c21ea18e5a24 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/2743d87d7934535f16a0ea062a28c21ea18e5a24/test_types.py
raise TestFailed, 'list index, negative stop argument'
raise TestFailed, 'list index, very -stop argument'
def __getitem__(self, key): return str(key) + '!!!'
2743d87d7934535f16a0ea062a28c21ea18e5a24 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/2743d87d7934535f16a0ea062a28c21ea18e5a24/test_types.py
header.append(mapping[2*i]+256*mapping[2*i+1])
if sys.byteorder == 'big': header.append(256*mapping[2*i]+mapping[2*i+1]) else: header.append(mapping[2*i]+256*mapping[2*i+1])
def _optimize_unicode(charset, fixup): charmap = [0]*65536 negate = 0 for op, av in charset: if op is NEGATE: negate = 1 elif op is LITERAL: charmap[fixup(av)] = 1 elif op is RANGE: for i in range(fixup(av[0]), fixup(av[1])+1): charmap[i] = 1 elif op is CATEGORY: # XXX: could expand category return charset # cannot compress if negate: for i in range(65536): charmap[i] = not charmap[i] comps = {} mapping = [0]*256 block = 0 data = [] for i in range(256): chunk = tuple(charmap[i*256:(i+1)*256]) new = comps.setdefault(chunk, block) mapping[i] = new if new == block: block += 1 data += _mk_bitmap(chunk) header = [block] assert MAXCODE == 65535 for i in range(128): header.append(mapping[2*i]+256*mapping[2*i+1]) data[0:0] = header return [(BIGCHARSET, data)]
3550dd30bb8cb880840a4f1f492a7f3e9207cab9 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/3550dd30bb8cb880840a4f1f492a7f3e9207cab9/sre_compile.py
bp = bdb.Breakpoint.bpbynumber[int(i)]
try: i = int(i) except ValueError: print 'Breakpoint index %r is not a number' % i continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): print 'No breakpoint numbered', i continue bp = bdb.Breakpoint.bpbynumber[i]
def do_enable(self, arg): args = arg.split() for i in args: bp = bdb.Breakpoint.bpbynumber[int(i)] if bp: bp.enable()
b1f8bab6542635cd32dfbebde3839f86819548ab /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/b1f8bab6542635cd32dfbebde3839f86819548ab/pdb.py
bp = bdb.Breakpoint.bpbynumber[int(i)]
try: i = int(i) except ValueError: print 'Breakpoint index %r is not a number' % i continue if not (0 <= i < len(bdb.Breakpoint.bpbynumber)): print 'No breakpoint numbered', i continue bp = bdb.Breakpoint.bpbynumber[i]
def do_disable(self, arg): args = arg.split() for i in args: bp = bdb.Breakpoint.bpbynumber[int(i)] if bp: bp.disable()
b1f8bab6542635cd32dfbebde3839f86819548ab /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/b1f8bab6542635cd32dfbebde3839f86819548ab/pdb.py
fp = open(pathname, "U")
if hasattr(sys.stdout, "newlines"): fp = open(pathname, "U") else: fp = open(pathname, "r")
def run_script(self, pathname): self.msg(2, "run_script", pathname) fp = open(pathname, "U") stuff = ("", "r", imp.PY_SOURCE) self.load_module('__main__', fp, pathname, stuff)
919000e9ec36c513f08253091b71a3aead2aff08 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/919000e9ec36c513f08253091b71a3aead2aff08/modulefinder.py
fp = open(pathname, "U")
if hasattr(sys.stdout, "newlines"): fp = open(pathname, "U") else: fp = open(pathname, "r")
def load_file(self, pathname): dir, name = os.path.split(pathname) name, ext = os.path.splitext(name) fp = open(pathname, "U") stuff = (ext, "r", imp.PY_SOURCE) self.load_module(name, fp, pathname, stuff)
919000e9ec36c513f08253091b71a3aead2aff08 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/919000e9ec36c513f08253091b71a3aead2aff08/modulefinder.py
def __init__(self, encoding=None):
def __init__(self, encoding=None, allow_none=0):
def __init__(self, encoding=None): self.memo = {} self.data = None self.encoding = encoding
a4c2b7485b6c33d0d6221d1a4505350ea9353668 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/a4c2b7485b6c33d0d6221d1a4505350ea9353668/xmlrpclib.py
self.allow_none = allow_none
def __init__(self, encoding=None): self.memo = {} self.data = None self.encoding = encoding
a4c2b7485b6c33d0d6221d1a4505350ea9353668 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/a4c2b7485b6c33d0d6221d1a4505350ea9353668/xmlrpclib.py
def dumps(params, methodname=None, methodresponse=None, encoding=None):
def dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=0):
def dumps(params, methodname=None, methodresponse=None, encoding=None): """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet. If this option is used with a tuple, the tuple must be a singleton (i.e. it can contain only one element). encoding: the packet encoding (default is UTF-8) All 8-bit strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, where necessary. """ assert isinstance(params, TupleType) or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if isinstance(params, Fault): methodresponse = 1 elif methodresponse and isinstance(params, TupleType): assert len(params) == 1, "response tuple must be a singleton" if not encoding: encoding = "utf-8" if FastMarshaller: m = FastMarshaller(encoding) else: m = Marshaller(encoding) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, StringType): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse: # a method response, or a fault structure data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return string.join(data, "")
a4c2b7485b6c33d0d6221d1a4505350ea9353668 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/a4c2b7485b6c33d0d6221d1a4505350ea9353668/xmlrpclib.py
m = Marshaller(encoding)
m = Marshaller(encoding, allow_none)
def dumps(params, methodname=None, methodresponse=None, encoding=None): """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the data object, the following options can be given as keyword arguments: methodname: the method name for a methodCall packet methodresponse: true to create a methodResponse packet. If this option is used with a tuple, the tuple must be a singleton (i.e. it can contain only one element). encoding: the packet encoding (default is UTF-8) All 8-bit strings in the data structure are assumed to use the packet encoding. Unicode strings are automatically converted, where necessary. """ assert isinstance(params, TupleType) or isinstance(params, Fault),\ "argument must be tuple or Fault instance" if isinstance(params, Fault): methodresponse = 1 elif methodresponse and isinstance(params, TupleType): assert len(params) == 1, "response tuple must be a singleton" if not encoding: encoding = "utf-8" if FastMarshaller: m = FastMarshaller(encoding) else: m = Marshaller(encoding) data = m.dumps(params) if encoding != "utf-8": xmlheader = "<?xml version='1.0' encoding='%s'?>\n" % str(encoding) else: xmlheader = "<?xml version='1.0'?>\n" # utf-8 is default # standard XML-RPC wrappings if methodname: # a method call if not isinstance(methodname, StringType): methodname = methodname.encode(encoding) data = ( xmlheader, "<methodCall>\n" "<methodName>", methodname, "</methodName>\n", data, "</methodCall>\n" ) elif methodresponse: # a method response, or a fault structure data = ( xmlheader, "<methodResponse>\n", data, "</methodResponse>\n" ) else: return data # return as is return string.join(data, "")
a4c2b7485b6c33d0d6221d1a4505350ea9353668 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/a4c2b7485b6c33d0d6221d1a4505350ea9353668/xmlrpclib.py
def __init__(self, uri, transport=None, encoding=None, verbose=0):
def __init__(self, uri, transport=None, encoding=None, verbose=0, allow_none=0):
def __init__(self, uri, transport=None, encoding=None, verbose=0): # establish a "logical" server connection
a4c2b7485b6c33d0d6221d1a4505350ea9353668 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/a4c2b7485b6c33d0d6221d1a4505350ea9353668/xmlrpclib.py
self.__allow_none = allow_none
def __init__(self, uri, transport=None, encoding=None, verbose=0): # establish a "logical" server connection
a4c2b7485b6c33d0d6221d1a4505350ea9353668 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/a4c2b7485b6c33d0d6221d1a4505350ea9353668/xmlrpclib.py
request = dumps(params, methodname, encoding=self.__encoding)
request = dumps(params, methodname, encoding=self.__encoding, allow_none=self.__allow_none)
def __request(self, methodname, params): # call a method on the remote server
a4c2b7485b6c33d0d6221d1a4505350ea9353668 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/a4c2b7485b6c33d0d6221d1a4505350ea9353668/xmlrpclib.py
server = ServerProxy("http://betty.userland.com")
server = ServerProxy("http://betty.userland.com")
def __getattr__(self, name): # magic method dispatcher return _Method(self.__request, name)
a4c2b7485b6c33d0d6221d1a4505350ea9353668 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/a4c2b7485b6c33d0d6221d1a4505350ea9353668/xmlrpclib.py
if value.sign == 1: self._sign = 0 else: self._sign = 1
self._sign = value.sign
def __new__(cls, value="0", context=None): """Create a decimal point instance.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
def __add__(self, other, context=None): """Returns self + other.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
diff = cmp(abs(op1), abs(op2))
def __add__(self, other, context=None): """Returns self + other.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
if diff == 0:
if op1.int == op2.int:
def __add__(self, other, context=None): """Returns self + other.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
if diff < 0:
if op1.int < op2.int:
def __add__(self, other, context=None): """Returns self + other.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
if op1.sign == -1: result.sign = -1
if op1.sign == 1: result.sign = 1
def __add__(self, other, context=None): """Returns self + other.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
result.sign = 1
result.sign = 0
def __add__(self, other, context=None): """Returns self + other.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
elif op1.sign == -1: result.sign = -1 op1.sign, op2.sign = (1, 1)
elif op1.sign == 1: result.sign = 1 op1.sign, op2.sign = (0, 0)
def __add__(self, other, context=None): """Returns self + other.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
result.sign = 1
result.sign = 0
def __add__(self, other, context=None): """Returns self + other.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
if op2.sign == 1:
if op2.sign == 0:
def __add__(self, other, context=None): """Returns self + other.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
if sign: sign = -1 else: sign = 1 adjust = 0
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
otherside = otherside._rescale(exp, context=context, watchexp=0)
otherside = otherside._rescale(exp, context=context, watchexp=0)
def _divide(self, other, divmod = 0, context=None): """Return a / b, to context.prec precision.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
def to_integral(self, a): """Rounds to an integer.
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
if isinstance(value, Decimal): if value._sign: self.sign = -1 else: self.sign = 1
elif isinstance(value, Decimal): self.sign = value._sign
def __init__(self, value=None): if value is None: self.sign = None self.int = 0 self.exp = None if isinstance(value, Decimal): if value._sign: self.sign = -1 else: self.sign = 1 cum = 0 for digit in value._int: cum = cum * 10 + digit self.int = cum self.exp = value._exp if isinstance(value, tuple): self.sign = value[0] self.int = value[1] self.exp = value[2]
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
for digit in value._int:
for digit in value._int:
def __init__(self, value=None): if value is None: self.sign = None self.int = 0 self.exp = None if isinstance(value, Decimal): if value._sign: self.sign = -1 else: self.sign = 1 cum = 0 for digit in value._int: cum = cum * 10 + digit self.int = cum self.exp = value._exp if isinstance(value, tuple): self.sign = value[0] self.int = value[1] self.exp = value[2]
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
if isinstance(value, tuple):
else:
def __init__(self, value=None): if value is None: self.sign = None self.int = 0 self.exp = None if isinstance(value, Decimal): if value._sign: self.sign = -1 else: self.sign = 1 cum = 0 for digit in value._int: cum = cum * 10 + digit self.int = cum self.exp = value._exp if isinstance(value, tuple): self.sign = value[0] self.int = value[1] self.exp = value[2]
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
def __neg__(self): if self.sign == 1: return _WorkRep( (-1, self.int, self.exp) ) else: return _WorkRep( (1, self.int, self.exp) ) def __abs__(self): if self.sign == -1: return -self else: return self def __cmp__(self, other): if self.exp != other.exp: raise ValueError("Operands not normalized: %r, %r" % (self, other)) if self.sign != other.sign: if self.sign == -1: return -1 else: return 1 if self.sign == -1: direction = -1 else: direction = 1 int1 = self.int int2 = other.int if int1 > int2: return direction * 1 if int1 < int2: return direction * -1 return 0
def __repr__(self): return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
17931de110ac84e6b0eb88d77a95798f8670765a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/17931de110ac84e6b0eb88d77a95798f8670765a/decimal.py
state = [kThemeStateActive, kThemeStateInactive][not onoff] App.DrawThemeListBoxFrame(Qd.InsetRect(self._bounds, 1, 1), state)
def activate(self, onoff): self._activated = onoff if self._visible: self._list.LActivate(onoff) state = [kThemeStateActive, kThemeStateInactive][not onoff] App.DrawThemeListBoxFrame(Qd.InsetRect(self._bounds, 1, 1), state) if self._selected: self.drawselframe(onoff)
59d5a9b5b7db3c84435d80224a825b8133654273 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/59d5a9b5b7db3c84435d80224a825b8133654273/Wlists.py
if isinstance(s, StringType):
if isinstance(s, str):
def _is8bitstring(s): if isinstance(s, StringType): try: unicode(s, 'us-ascii') except UnicodeError: return True return False
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
self.__maxheaderlen = maxheaderlen
self._maxheaderlen = maxheaderlen
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78): """Create the generator for message flattening.
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
return self.__class__(fp, self._mangle_from_, self.__maxheaderlen)
return self.__class__(fp, self._mangle_from_, self._maxheaderlen)
def clone(self, fp): """Clone this generator with the exact same options.""" return self.__class__(fp, self._mangle_from_, self.__maxheaderlen)
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
if self.__maxheaderlen == 0:
if self._maxheaderlen == 0:
def _write_headers(self, msg): for h, v in msg.items(): print >> self._fp, '%s:' % h, if self.__maxheaderlen == 0: # Explicit no-wrapping print >> self._fp, v elif isinstance(v, Header): # Header instances know what to do print >> self._fp, v.encode() elif _is8bitstring(v): # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this # string. If it's ascii-subset, then we could do a normal # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. print >> self._fp, v else: # Header's got lots of smarts, so use it. print >> self._fp, Header( v, maxlinelen=self.__maxheaderlen, header_name=h, continuation_ws='\t').encode() # A blank line always separates headers from body print >> self._fp
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
v, maxlinelen=self.__maxheaderlen,
v, maxlinelen=self._maxheaderlen,
def _write_headers(self, msg): for h, v in msg.items(): print >> self._fp, '%s:' % h, if self.__maxheaderlen == 0: # Explicit no-wrapping print >> self._fp, v elif isinstance(v, Header): # Header instances know what to do print >> self._fp, v.encode() elif _is8bitstring(v): # If we have raw 8bit data in a byte string, we have no idea # what the encoding is. There is no safe way to split this # string. If it's ascii-subset, then we could do a normal # ascii split, but if it's multibyte then we could break the # string. There's no way to know so the least harm seems to # be to not split the string and risk it being too long. print >> self._fp, v else: # Header's got lots of smarts, so use it. print >> self._fp, Header( v, maxlinelen=self.__maxheaderlen, header_name=h, continuation_ws='\t').encode() # A blank line always separates headers from body print >> self._fp
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
if not _isstring(payload):
if not isinstance(payload, basestring):
def _handle_text(self, msg): payload = msg.get_payload() if payload is None: return cset = msg.get_charset() if cset is not None: payload = cset.body_encode(payload) if not _isstring(payload): raise TypeError, 'string payload expected: %s' % type(payload) if self._mangle_from_: payload = fcre.sub('>From ', payload) self._fp.write(payload)
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts):
subparts = [] elif isinstance(subparts, basestring):
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # If preamble is the empty string, the length of the split will be # 1, but the last element will be the empty string. If it's # anything else but does not end in a line separator, the length # will be > 1 and not end in an empty string. We need to # guarantee a newline after the preamble, but don't add too many. plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n') # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
elif not isinstance(subparts, ListType):
elif not isinstance(subparts, list):
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # If preamble is the empty string, the length of the split will be # 1, but the last element will be the empty string. If it's # anything else but does not end in a line separator, the length # will be > 1 and not end in an empty string. We need to # guarantee a newline after the preamble, but don't add too many. plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n') # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # If preamble is the empty string, the length of the split will be # 1, but the last element will be the empty string. If it's # anything else but does not end in a line separator, the length # will be > 1 and not end in an empty string. We need to # guarantee a newline after the preamble, but don't add too many. plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n') # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
self._fp.write(msg.preamble) plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n')
print >> self._fp, msg.preamble
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # If preamble is the empty string, the length of the split will be # 1, but the last element will be the empty string. If it's # anything else but does not end in a line separator, the length # will be > 1 and not end in an empty string. We need to # guarantee a newline after the preamble, but don't add too many. plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n') # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--',
if msgtexts: self._fp.write(msgtexts.pop(0)) for body_part in msgtexts: print >> self._fp, '\n--' + boundary self._fp.write(body_part) self._fp.write('\n--' + boundary + '--')
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # If preamble is the empty string, the length of the split will be # 1, but the last element will be the empty string. If it's # anything else but does not end in a line separator, the length # will be > 1 and not end in an empty string. We need to # guarantee a newline after the preamble, but don't add too many. plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n') # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
if not msg.epilogue.startswith('\n'): print >> self._fp
print >> self._fp
def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # If preamble is the empty string, the length of the split will be # 1, but the last element will be the empty string. If it's # anything else but does not end in a line separator, the length # will be > 1 and not end in an empty string. We need to # guarantee a newline after the preamble, but don't add too many. plines = NLCRE.split(msg.preamble) if plines <> [''] and plines[-1] <> '': self._fp.write('\n') # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue)
36112f2d34253c36784302cb703977ec78ccc7b2 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/36112f2d34253c36784302cb703977ec78ccc7b2/Generator.py
filename = words[-1] infostuff = words[-5:-1]
filename = string.join(words[8:]) infostuff = words[5:]
def mirrorsubdir(f, localdir): pwd = f.pwd() if localdir and not os.path.isdir(localdir): if verbose: print 'Creating local directory', localdir try: makedir(localdir) except os.error, msg: print "Failed to establish local directory", localdir return infofilename = os.path.join(localdir, '.mirrorinfo') try: text = open(infofilename, 'r').read() except IOError, msg: text = '{}' try: info = eval(text) except (SyntaxError, NameError): print 'Bad mirror info in %s' % infofilename info = {} subdirs = [] listing = [] if verbose: print 'Listing remote directory %s...' % pwd f.retrlines('LIST', listing.append) filesfound = [] for line in listing: if verbose > 1: print '-->', `line` if mac: # Mac listing has just filenames; # trailing / means subdirectory filename = string.strip(line) mode = '-' if filename[-1:] == '/': filename = filename[:-1] mode = 'd' infostuff = '' else: # Parse, assuming a UNIX listing words = string.split(line) if len(words) < 6: if verbose > 1: print 'Skipping short line' continue if words[-2] == '->': if verbose > 1: print 'Skipping symbolic link %s -> %s' % \ (words[-3], words[-1]) continue filename = words[-1] infostuff = words[-5:-1] mode = words[0] skip = 0 for pat in skippats: if fnmatch(filename, pat): if verbose > 1: print 'Skip pattern', pat, print 'matches', filename skip = 1 break if skip: continue if mode[0] == 'd': if verbose > 1: print 'Remembering subdirectory', filename subdirs.append(filename) continue filesfound.append(filename) if info.has_key(filename) and info[filename] == infostuff: if verbose > 1: print 'Already have this version of', filename continue fullname = os.path.join(localdir, filename) tempname = os.path.join(localdir, '@'+filename) if interactive: doit = askabout('file', filename, pwd) if not doit: if not info.has_key(filename): info[filename] = 'Not retrieved' continue try: os.unlink(tempname) except os.error: pass try: fp = open(tempname, 'wb') except IOError, msg: print "Can't create %s: %s" % (tempname, str(msg)) continue if verbose: print 'Retrieving %s from %s as %s...' % \ (filename, pwd, fullname) if verbose: fp1 = LoggingFile(fp, 1024, sys.stdout) else: fp1 = fp t0 = time.time() try: f.retrbinary('RETR ' + filename, fp1.write, 8*1024) except ftplib.error_perm, msg: print msg t1 = time.time() bytes = fp.tell() fp.close() if fp1 != fp: fp1.close() try: os.unlink(fullname) except os.error: pass # Ignore the error try: os.rename(tempname, fullname) except os.error, msg: print "Can't rename %s to %s: %s" % (tempname, fullname, str(msg)) continue info[filename] = infostuff writedict(info, infofilename) if verbose: dt = t1 - t0 kbytes = bytes / 1024.0 print int(round(kbytes)), print 'Kbytes in', print int(round(dt)), print 'seconds', if t1 > t0: print '(~%d Kbytes/sec)' % \ int(round(kbytes/dt),) print # # Remove files from info that are no longer remote deletions = 0 for filename in info.keys(): if filename not in filesfound: if verbose: print "Removing obsolete info entry for", print filename, "in", localdir or "." del info[filename] deletions = deletions + 1 if deletions: writedict(info, infofilename) # # Remove local files that are no longer in the remote directory try: if not localdir: names = os.listdir(os.curdir) else: names = os.listdir(localdir) except os.error: names = [] for name in names: if name[0] == '.' or info.has_key(name) or name in subdirs: continue skip = 0 for pat in skippats: if fnmatch(name, pat): if verbose > 1: print 'Skip pattern', pat, print 'matches', name skip = 1 break if skip: continue fullname = os.path.join(localdir, name) if not rmok: if verbose: print 'Local file', fullname, print 'is no longer pertinent' continue if verbose: print 'Removing local file/dir', fullname remove(fullname) # # Recursively mirror subdirectories for subdir in subdirs: if interactive: doit = askabout('subdirectory', subdir, pwd) if not doit: continue if verbose: print 'Processing subdirectory', subdir localsubdir = os.path.join(localdir, subdir) pwd = f.pwd() if verbose > 1: print 'Remote directory now:', pwd print 'Remote cwd', subdir try: f.cwd(subdir) except ftplib.error_perm, msg: print "Can't chdir to", subdir, ":", msg else: if verbose: print 'Mirroring as', localsubdir mirrorsubdir(f, localsubdir) if verbose > 1: print 'Remote cwd ..' f.cwd('..') newpwd = f.pwd() if newpwd != pwd: print 'Ended up in wrong directory after cd + cd ..' print 'Giving up now.' break else: if verbose > 1: print 'OK.'
aeeda5b276e26eafa8c1e8fa8af08c0af7d7f34c /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/aeeda5b276e26eafa8c1e8fa8af08c0af7d7f34c/ftpmirror.py
assert output_dir is not None
if output_dir is None: output_dir = ''
def object_filenames(self, source_filenames, strip_dir=0, output_dir=''): assert output_dir is not None obj_names = [] for src_name in source_filenames: base, ext = os.path.splitext(src_name) if ext not in self.src_extensions: raise UnknownFileError, \ "unknown file type '%s' (from '%s')" % (ext, src_name) if strip_dir: base = os.path.basename(base) obj_names.append(os.path.join(output_dir, base + self.obj_extension)) return obj_names
cc3a6df506db57d614225b3657b4e97efc078970 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/cc3a6df506db57d614225b3657b4e97efc078970/ccompiler.py
strip_dir=python_build,
strip_dir=0,
def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra): """Process arguments and decide which source files to compile.
ad647859f4e45af749ca2f5a5bc45aaad3b1ca20 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/ad647859f4e45af749ca2f5a5bc45aaad3b1ca20/ccompiler.py
objects = self.object_filenames(sources, strip_dir=python_build, output_dir=output_dir)
objects = self.object_filenames(sources, output_dir=output_dir)
def _prep_compile(self, sources, output_dir, depends=None): """Decide which souce files must be recompiled.
ad647859f4e45af749ca2f5a5bc45aaad3b1ca20 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/ad647859f4e45af749ca2f5a5bc45aaad3b1ca20/ccompiler.py
uchunks = [unicode(s, str(charset)) for s, charset in self._chunks] return u''.join(uchunks)
uchunks = [] lastcs = None for s, charset in self._chunks: nextcs = charset if uchunks: if lastcs is not None: if nextcs is None or nextcs == 'us-ascii': uchunks.append(USPACE) nextcs = None elif nextcs is not None and nextcs <> 'us-ascii': uchunks.append(USPACE) lastcs = nextcs uchunks.append(unicode(s, str(charset))) return UEMPTYSTRING.join(uchunks)
def __unicode__(self): """Helper for the built-in unicode function.""" # charset item is a Charset instance so we need to stringify it. uchunks = [unicode(s, str(charset)) for s, charset in self._chunks] return u''.join(uchunks)
484880534160893c610e5e3a723cf8a3d9f8f116 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/484880534160893c610e5e3a723cf8a3d9f8f116/Header.py
_urandomfd = None
def _pickle_statvfs_result(sr): (type, args) = sr.__reduce__() return (_make_statvfs_result, args)
9e43acf2f31e67a976475c2c9f8674dd27571cc6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/9e43acf2f31e67a976475c2c9f8674dd27571cc6/os.py
global _urandomfd if _urandomfd is None: try: _urandomfd = open("/dev/urandom", O_RDONLY) except: _urandomfd = NotImplementedError if _urandomfd is NotImplementedError:
try: _urandomfd = open("/dev/urandom", O_RDONLY) except:
def urandom(n): """urandom(n) -> str
9e43acf2f31e67a976475c2c9f8674dd27571cc6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/9e43acf2f31e67a976475c2c9f8674dd27571cc6/os.py
value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value == output and type(value) is type(output):
value = f(*args) self.assertEqual(output, value) self.assert_(type(output) is type(value))
def test(method, input, output, *args): if verbose: print '%s.%s%s =? %s... ' % (repr(input), method, args, repr(output)), try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] else: exc = None if value == output and type(value) is type(output): # if the original is returned make sure that # this doesn't happen with subclasses if value is input: class usub(unicode): def __repr__(self): return 'usub(%r)' % unicode.__repr__(self) input = usub(input) try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] if value is input: if verbose: print 'no' print '*',f, `input`, `output`, `value` return if value != output or type(value) is not type(output): if verbose: print 'no' print '*',f, `input`, `output`, `value` if exc: print ' value == %s: %s' % (exc) else: if verbose: print 'yes'
28256f276e1d61d54301b874958fc78c26117c9e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/28256f276e1d61d54301b874958fc78c26117c9e/test_unicode.py
try: f = getattr(input, method) value = apply(f, args) except: value = sys.exc_type exc = sys.exc_info()[:2] if value is input: if verbose: print 'no' print '*',f, `input`, `output`, `value` return if value != output or type(value) is not type(output): if verbose: print 'no' print '*',f, `input`, `output`, `value` if exc: print ' value == %s: %s' % (exc) else: if verbose: print 'yes' test('capitalize', u' hello ', u' hello ') test('capitalize', u'Hello ', u'Hello ') test('capitalize', u'hello ', u'Hello ') test('capitalize', u'aaaa', u'Aaaa') test('capitalize', u'AaAa', u'Aaaa') test('count', u'aaa', 3, u'a') test('count', u'aaa', 0, u'b') test('count', 'aaa', 3, u'a') test('count', 'aaa', 0, u'b') test('count', u'aaa', 3, 'a') test('count', u'aaa', 0, 'b') test('title', u' hello ', u' Hello ') test('title', u'Hello ', u'Hello ') test('title', u'hello ', u'Hello ') test('title', u"fOrMaT thIs aS titLe String", u'Format This As Title String') test('title', u"fOrMaT,thIs-aS*titLe;String", u'Format,This-As*Title;String') test('title', u"getInt", u'Getint') test('find', u'abcdefghiabc', 0, u'abc') test('find', u'abcdefghiabc', 9, u'abc', 1) test('find', u'abcdefghiabc', -1, u'def', 4) test('rfind', u'abcdefghiabc', 9, u'abc') test('rfind', 'abcdefghiabc', 9, u'abc') test('rfind', 'abcdefghiabc', 12, u'') test('rfind', u'abcdefghiabc', 12, '') test('rfind', u'abcdefghiabc', 12, u'') test('lower', u'HeLLo', u'hello') test('lower', u'hello', u'hello') test('upper', u'HeLLo', u'HELLO') test('upper', u'HELLO', u'HELLO') if 0: transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !" test('maketrans', u'abc', transtable, u'xyz') test('maketrans', u'abc', ValueError, u'xyzq') test('split', u'this is the split function', [u'this', u'is', u'the', u'split', u'function']) test('split', u'a|b|c|d', [u'a', u'b', u'c', u'd'], u'|') test('split', u'a|b|c|d', [u'a', u'b', u'c|d'], u'|', 2) test('split', u'a b c d', [u'a', u'b c d'], None, 1) test('split', u'a b c d', [u'a', u'b', u'c d'], None, 2) test('split', u'a b c d', [u'a', u'b', u'c', u'd'], None, 3) test('split', u'a b c d', [u'a', u'b', u'c', u'd'], None, 4) test('split', u'a b c d', [u'a b c d'], None, 0) test('split', u'a b c d', [u'a', u'b', u'c d'], None, 2) test('split', u'a b c d ', [u'a', u'b', u'c', u'd']) test('split', u'a//b//c//d', [u'a', u'b', u'c', u'd'], u'//') test('split', u'a//b//c//d', [u'a', u'b', u'c', u'd'], '//') test('split', 'a//b//c//d', [u'a', u'b', u'c', u'd'], u'//') test('split', u'endcase test', [u'endcase ', u''], u'test') test('split', u'endcase test', [u'endcase ', u''], 'test') test('split', 'endcase test', [u'endcase ', u''], u'test') class Sequence: def __init__(self, seq): self.seq = seq def __len__(self): return len(self.seq) def __getitem__(self, i): return self.seq[i] test('join', u' ', u'a b c d', [u'a', u'b', u'c', u'd']) test('join', u' ', u'a b c d', ['a', 'b', u'c', u'd']) test('join', u'', u'abcd', (u'a', u'b', u'c', u'd')) test('join', u' ', u'w x y z', Sequence('wxyz')) test('join', u' ', TypeError, 7) test('join', u' ', TypeError, Sequence([7, u'hello', 123L])) test('join', ' ', u'a b c d', [u'a', u'b', u'c', u'd']) test('join', ' ', u'a b c d', ['a', 'b', u'c', u'd']) test('join', '', u'abcd', (u'a', u'b', u'c', u'd')) test('join', ' ', u'w x y z', Sequence(u'wxyz')) test('join', ' ', TypeError, 7) result = u'' for i in range(10): if i > 0: result = result + u':' result = result + u'x'*10 test('join', u':', result, [u'x' * 10] * 10) test('join', u':', result, (u'x' * 10,) * 10) test('strip', u' hello ', u'hello') test('lstrip', u' hello ', u'hello ') test('rstrip', u' hello ', u' hello') test('strip', u'hello', u'hello') test('strip', u' hello ', u'hello', None) test('lstrip', u' hello ', u'hello ', None) test('rstrip', u' hello ', u' hello', None) test('strip', u'hello', u'hello', None) test('strip', u'xyzzyhelloxyzzy', u'hello', u'xyz') test('lstrip', u'xyzzyhelloxyzzy', u'helloxyzzy', u'xyz') test('rstrip', u'xyzzyhelloxyzzy', u'xyzzyhello', u'xyz') test('strip', u'hello', u'hello', u'xyz') test('strip', u'xyzzyhelloxyzzy', u'hello', 'xyz') test('lstrip', u'xyzzyhelloxyzzy', u'helloxyzzy', 'xyz') test('rstrip', u'xyzzyhelloxyzzy', u'xyzzyhello', 'xyz') test('strip', u'hello', u'hello', 'xyz') test('swapcase', u'HeLLo cOmpUteRs', u'hEllO CoMPuTErS') if 0: test('translate', u'xyzabcdef', u'xyzxyz', transtable, u'def') table = string.maketrans('a', u'A') test('translate', u'abc', u'Abc', table) test('translate', u'xyz', u'xyz', table) test('replace', u'one!two!three!', u'one@two!three!', u'!', u'@', 1) test('replace', u'one!two!three!', u'onetwothree', '!', '') test('replace', u'one!two!three!', u'one@two@three!', u'!', u'@', 2) test('replace', u'one!two!three!', u'one@two@three@', u'!', u'@', 3) test('replace', u'one!two!three!', u'one@two@three@', u'!', u'@', 4) test('replace', u'one!two!three!', u'one!two!three!', u'!', u'@', 0) test('replace', u'one!two!three!', u'one@two@three@', u'!', u'@') test('replace', u'one!two!three!', u'one!two!three!', u'x', u'@') test('replace', u'one!two!three!', u'one!two!three!', u'x', u'@', 2) test('replace', u'abc', u'-a-b-c-', u'', u'-') test('replace', u'abc', u'-a-b-c', u'', u'-', 3) test('replace', u'abc', u'abc', u'', u'-', 0) test('replace', u'abc', u'abc', u'ab', u'--', 0) test('replace', u'abc', u'abc', u'xy', u'--') test('replace', u'', u'', u'', u'') test('startswith', u'hello', True, u'he') test('startswith', u'hello', True, u'hello') test('startswith', u'hello', False, u'hello world') test('startswith', u'hello', True, u'') test('startswith', u'hello', False, u'ello') test('startswith', u'hello', True, u'ello', 1) test('startswith', u'hello', True, u'o', 4) test('startswith', u'hello', False, u'o', 5) test('startswith', u'hello', True, u'', 5) test('startswith', u'hello', False, u'lo', 6) test('startswith', u'helloworld', True, u'lowo', 3) test('startswith', u'helloworld', True, u'lowo', 3, 7) test('startswith', u'helloworld', False, u'lowo', 3, 6) test('endswith', u'hello', True, u'lo') test('endswith', u'hello', False, u'he') test('endswith', u'hello', True, u'') test('endswith', u'hello', False, u'hello world') test('endswith', u'helloworld', False, u'worl') test('endswith', u'helloworld', True, u'worl', 3, 9) test('endswith', u'helloworld', True, u'world', 3, 12) test('endswith', u'helloworld', True, u'lowo', 1, 7) test('endswith', u'helloworld', True, u'lowo', 2, 7) test('endswith', u'helloworld', True, u'lowo', 3, 7) test('endswith', u'helloworld', False, u'lowo', 4, 7) test('endswith', u'helloworld', False, u'lowo', 3, 8) test('endswith', u'ab', False, u'ab', 0, 1) test('endswith', u'ab', False, u'ab', 0, 0) test('endswith', 'helloworld', True, u'd') test('endswith', 'helloworld', False, u'l') test('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab def\ng hi') test('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab def\ng hi', 8) test('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab def\ng hi', 4) test('expandtabs', u'abc\r\nab\tdef\ng\thi', u'abc\r\nab def\ng hi', 4) test('expandtabs', u'abc\r\nab\r\ndef\ng\r\nhi', u'abc\r\nab\r\ndef\ng\r\nhi', 4) if 0: test('capwords', u'abc def ghi', u'Abc Def Ghi') test('capwords', u'abc\tdef\nghi', u'Abc Def Ghi') test('capwords', u'abc\t def \nghi', u'Abc Def Ghi') test('zfill', u'123', u'123', 2) test('zfill', u'123', u'123', 3) test('zfill', u'123', u'0123', 4) test('zfill', u'+123', u'+123', 3) test('zfill', u'+123', u'+123', 4) test('zfill', u'+123', u'+0123', 5) test('zfill', u'-123', u'-123', 3) test('zfill', u'-123', u'-123', 4) test('zfill', u'-123', u'-0123', 5) test('zfill', u'', u'000', 3) test('zfill', u'34', u'34', 1) test('zfill', u'34', u'00034', 5) print 'Testing Unicode comparisons...', verify(u'abc' == 'abc') verify('abc' == u'abc') verify(u'abc' == u'abc') verify(u'abcd' > 'abc') verify('abcd' > u'abc') verify(u'abcd' > u'abc') verify(u'abc' < 'abcd') verify('abc' < u'abcd') verify(u'abc' < u'abcd') print 'done.' if 0: print 'Testing UTF-16 code point order comparisons...', verify(u'\u0061' < u'\u20ac') verify(u'\u0061' < u'\ud800\udc02') def test_lecmp(s, s2): verify(s < s2 , "comparison failed on %s < %s" % (s, s2)) def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_lecmp(s, s2) s2 = u'\ud800\ude01' test_lecmp(s, s2) s2 = u'\ud900\ude01' test_lecmp(s, s2) s2 = u'\uda00\ude01' test_lecmp(s, s2) s2 = u'\udb00\ude01' test_lecmp(s, s2) s2 = u'\ud800\udfff' test_lecmp(s, s2) s2 = u'\ud900\udfff' test_lecmp(s, s2) s2 = u'\uda00\udfff' test_lecmp(s, s2) s2 = u'\udb00\udfff' test_lecmp(s, s2) test_fixup(u'\ue000') test_fixup(u'\uff61') verify(u'\ud800\udc02' < u'\ud84d\udc56') print 'done.' test('ljust', u'abc', u'abc ', 10) test('rjust', u'abc', u' abc', 10) test('center', u'abc', u' abc ', 10) test('ljust', u'abc', u'abc ', 6) test('rjust', u'abc', u' abc', 6) test('center', u'abc', u' abc ', 6) test('ljust', u'abc', u'abc', 2) test('rjust', u'abc', u'abc', 2) test('center', u'abc', u'abc', 2) test('islower', u'a', True) test('islower', u'A', False) test('islower', u'\n', False) test('islower', u'\u1FFc', False) test('islower', u'abc', True) test('islower', u'aBc', False) test('islower', u'abc\n', True) test('isupper', u'a', False) test('isupper', u'A', True) test('isupper', u'\n', False) if sys.platform[:4] != 'java': test('isupper', u'\u1FFc', False) test('isupper', u'ABC', True) test('isupper', u'AbC', False) test('isupper', u'ABC\n', True) test('istitle', u'a', False) test('istitle', u'A', True) test('istitle', u'\n', False) test('istitle', u'\u1FFc', True) test('istitle', u'A Titlecased Line', True) test('istitle', u'A\nTitlecased Line', True) test('istitle', u'A Titlecased, Line', True) test('istitle', u'Greek \u1FFcitlecases ...', True) test('istitle', u'Not a capitalized String', False) test('istitle', u'Not\ta Titlecase String', False) test('istitle', u'Not--a Titlecase String', False) test('isalpha', u'a', True) test('isalpha', u'A', True) test('isalpha', u'\n', False) test('isalpha', u'\u1FFc', True) test('isalpha', u'abc', True) test('isalpha', u'aBc123', False) test('isalpha', u'abc\n', False) test('isalnum', u'a', True) test('isalnum', u'A', True) test('isalnum', u'\n', False) test('isalnum', u'123abc456', True) test('isalnum', u'a1b3c', True) test('isalnum', u'aBc000 ', False) test('isalnum', u'abc\n', False) test('splitlines', u"abc\ndef\n\rghi", [u'abc', u'def', u'', u'ghi']) test('splitlines', u"abc\ndef\n\r\nghi", [u'abc', u'def', u'', u'ghi']) test('splitlines', u"abc\ndef\r\nghi", [u'abc', u'def', u'ghi']) test('splitlines', u"abc\ndef\r\nghi\n", [u'abc', u'def', u'ghi']) test('splitlines', u"abc\ndef\r\nghi\n\r", [u'abc', u'def', u'ghi', u'']) test('splitlines', u"\nabc\ndef\r\nghi\n\r", [u'', u'abc', u'def', u'ghi', u'']) test('splitlines', u"\nabc\ndef\r\nghi\n\r", [u'\n', u'abc\n', u'def\r\n', u'ghi\n', u'\r'], True) test('translate', u"abababc", u'bbbc', {ord('a'):None}) test('translate', u"abababc", u'iiic', {ord('a'):None, ord('b'):ord('i')}) test('translate', u"abababc", u'iiix', {ord('a'):None, ord('b'):ord('i'), ord('c'):u'x'}) test('translate', u"abababc", u'<i><i><i>c', {ord('a'):None, ord('b'):u'<i>'}) test('translate', u"abababc", u'c', {ord('a'):None, ord('b'):u''}) print 'Testing Unicode contains method...', vereq(('a' in u'abdb'), True) vereq(('a' in u'bdab'), True) vereq(('a' in u'bdaba'), True) vereq(('a' in u'bdba'), True) vereq(('a' in u'bdba'), True) vereq((u'a' in u'bdba'), True) vereq((u'a' in u'bdb'), False) vereq((u'a' in 'bdb'), False) vereq((u'a' in 'bdba'), True) vereq((u'a' in ('a',1,None)), True) vereq((u'a' in (1,None,'a')), True) vereq((u'a' in (1,None,u'a')), True) vereq(('a' in ('a',1,None)), True) vereq(('a' in (1,None,'a')), True) vereq(('a' in (1,None,u'a')), True) vereq(('a' in ('x',1,u'y')), False) vereq(('a' in ('x',1,None)), False) vereq(u'abcd' in u'abcxxxx', False) vereq((u'ab' in u'abcd'), True) vereq(('ab' in u'abc'), True) vereq((u'ab' in 'abc'), True) vereq((u'ab' in (1,None,u'ab')), True) vereq((u'' in u'abc'), True) vereq(('' in u'abc'), True) try: u'\xe2' in 'g\xe2teau' except UnicodeError: pass else: print '*** contains operator does not propagate UnicodeErrors' print 'done.' print 'Testing Unicode formatting strings...', verify(u"%s, %s" % (u"abc", "abc") == u'abc, abc') verify(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", 1, 2, 3) == u'abc, abc, 1, 2.000000, 3.00') verify(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", 1, -2, 3) == u'abc, abc, 1, -2.000000, 3.00') verify(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.5) == u'abc, abc, -1, -2.000000, 3.50') verify(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.57) == u'abc, abc, -1, -2.000000, 3.57') verify(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 1003.57) == u'abc, abc, -1, -2.000000, 1003.57') verify(u"%c" % (u"a",) == u'a') verify(u"%c" % ("a",) == u'a') verify(u"%c" % (34,) == u'"') verify(u"%c" % (36,) == u'$') verify(u"%d".__mod__(10) == u'10') if sys.platform[:4] != 'java': value = u"%r, %r" % (u"abc", "abc") if value != u"u'abc', 'abc'": print '*** formatting failed for "%s"' % 'u"%r, %r" % (u"abc", "abc")' verify(u"%(x)s, %(y)s" % {'x':u"abc", 'y':"def"} == u'abc, def') try: value = u"%(x)s, %()s" % {'x':u"abc", u'':"def"} except KeyError: print '*** formatting failed for "%s"' % "u'abc, def'" else: verify(value == u'abc, def') for ordinal in (-100, 0x200000): try: u"%c" % ordinal except ValueError: pass else: print '*** formatting u"%%c" %% %i should give a ValueError' % ordinal for prec in range(100): formatstring = u'%%.%if' % prec value = 0.01 for x in range(60): value = value * 3.141592655 / 3.0 * 10.0 try: result = formatstring % value except OverflowError: if x >= 50 or \ prec < 67: print '*** unexpected OverflowError for x=%i and prec=%i' % (x, prec)
f = getattr(input, method) value = f(*args) self.assertEqual(output, value) self.assert_(input is not value) def test_capitalize(self): self.checkmethod('capitalize', u' hello ', u' hello ') self.checkmethod('capitalize', u'Hello ', u'Hello ') self.checkmethod('capitalize', u'hello ', u'Hello ') self.checkmethod('capitalize', u'aaaa', u'Aaaa') self.checkmethod('capitalize', u'AaAa', u'Aaaa') self.assertRaises(TypeError, u'hello'.capitalize, 42) def test_count(self): self.checkmethod('count', u'aaa', 3, u'a') self.checkmethod('count', u'aaa', 0, u'b') self.checkmethod('count', 'aaa', 3, u'a') self.checkmethod('count', 'aaa', 0, u'b') self.checkmethod('count', u'aaa', 3, 'a') self.checkmethod('count', u'aaa', 0, 'b') self.assertRaises(TypeError, u'hello'.count) def test_title(self): self.checkmethod('title', u' hello ', u' Hello ') self.checkmethod('title', u'Hello ', u'Hello ') self.checkmethod('title', u'hello ', u'Hello ') self.checkmethod('title', u"fOrMaT thIs aS titLe String", u'Format This As Title String') self.checkmethod('title', u"fOrMaT,thIs-aS*titLe;String", u'Format,This-As*Title;String') self.checkmethod('title', u"getInt", u'Getint') self.assertRaises(TypeError, u'hello'.count, 42) def test_find(self): self.checkmethod('find', u'abcdefghiabc', 0, u'abc') self.checkmethod('find', u'abcdefghiabc', 9, u'abc', 1) self.checkmethod('find', u'abcdefghiabc', -1, u'def', 4) self.assertRaises(TypeError, u'hello'.find) self.assertRaises(TypeError, u'hello'.find, 42) def test_rfind(self): self.checkmethod('rfind', u'abcdefghiabc', 9, u'abc') self.checkmethod('rfind', 'abcdefghiabc', 9, u'abc') self.checkmethod('rfind', 'abcdefghiabc', 12, u'') self.checkmethod('rfind', u'abcdefghiabc', 12, '') self.checkmethod('rfind', u'abcdefghiabc', 12, u'') self.assertRaises(TypeError, u'hello'.rfind) self.assertRaises(TypeError, u'hello'.rfind, 42) def test_index(self): self.checkmethod('index', u'abcdefghiabc', 0, u'') self.checkmethod('index', u'abcdefghiabc', 3, u'def') self.checkmethod('index', u'abcdefghiabc', 0, u'abc') self.checkmethod('index', u'abcdefghiabc', 9, u'abc', 1) self.assertRaises(ValueError, u'abcdefghiabc'.index, u'hib') self.assertRaises(ValueError, u'abcdefghiab'.index, u'abc', 1) self.assertRaises(ValueError, u'abcdefghi'.index, u'ghi', 8) self.assertRaises(ValueError, u'abcdefghi'.index, u'ghi', -1) self.assertRaises(TypeError, u'hello'.index) self.assertRaises(TypeError, u'hello'.index, 42) def test_rindex(self): self.checkmethod('rindex', u'abcdefghiabc', 12, u'') self.checkmethod('rindex', u'abcdefghiabc', 3, u'def') self.checkmethod('rindex', u'abcdefghiabc', 9, u'abc') self.checkmethod('rindex', u'abcdefghiabc', 0, u'abc', 0, -1) self.assertRaises(ValueError, u'abcdefghiabc'.rindex, u'hib') self.assertRaises(ValueError, u'defghiabc'.rindex, u'def', 1) self.assertRaises(ValueError, u'defghiabc'.rindex, u'abc', 0, -1) self.assertRaises(ValueError, u'abcdefghi'.rindex, u'ghi', 0, 8) self.assertRaises(ValueError, u'abcdefghi'.rindex, u'ghi', 0, -1) self.assertRaises(TypeError, u'hello'.rindex) self.assertRaises(TypeError, u'hello'.rindex, 42) def test_lower(self): self.checkmethod('lower', u'HeLLo', u'hello') self.checkmethod('lower', u'hello', u'hello') self.assertRaises(TypeError, u"hello".lower, 42) def test_upper(self): self.checkmethod('upper', u'HeLLo', u'HELLO') self.checkmethod('upper', u'HELLO', u'HELLO') self.assertRaises(TypeError, u'hello'.upper, 42) def test_translate(self): if 0: transtable = '\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !" self.checkmethod('maketrans', u'abc', transtable, u'xyz') self.checkmethod('maketrans', u'abc', ValueError, u'xyzq') self.checkmethod('translate', u'xyzabcdef', u'xyzxyz', transtable, u'def') table = string.maketrans('a', u'A') self.checkmethod('translate', u'abc', u'Abc', table) self.checkmethod('translate', u'xyz', u'xyz', table) self.checkmethod('translate', u"abababc", u'bbbc', {ord('a'):None}) self.checkmethod('translate', u"abababc", u'iiic', {ord('a'):None, ord('b'):ord('i')}) self.checkmethod('translate', u"abababc", u'iiix', {ord('a'):None, ord('b'):ord('i'), ord('c'):u'x'}) self.checkmethod('translate', u"abababc", u'<i><i><i>c', {ord('a'):None, ord('b'):u'<i>'}) self.checkmethod('translate', u"abababc", u'c', {ord('a'):None, ord('b'):u''}) self.assertRaises(TypeError, u'hello'.translate) def test_split(self): self.checkmethod( 'split', u'this is the split function', [u'this', u'is', u'the', u'split', u'function'] ) self.checkmethod('split', u'a|b|c|d', [u'a', u'b', u'c', u'd'], u'|') self.checkmethod('split', u'a|b|c|d', [u'a', u'b', u'c|d'], u'|', 2) self.checkmethod('split', u'a b c d', [u'a', u'b c d'], None, 1) self.checkmethod('split', u'a b c d', [u'a', u'b', u'c d'], None, 2) self.checkmethod('split', u'a b c d', [u'a', u'b', u'c', u'd'], None, 3) self.checkmethod('split', u'a b c d', [u'a', u'b', u'c', u'd'], None, 4) self.checkmethod('split', u'a b c d', [u'a b c d'], None, 0) self.checkmethod('split', u'a b c d', [u'a', u'b', u'c d'], None, 2) self.checkmethod('split', u'a b c d ', [u'a', u'b', u'c', u'd']) self.checkmethod('split', u'a//b//c//d', [u'a', u'b', u'c', u'd'], u'//') self.checkmethod('split', u'a//b//c//d', [u'a', u'b', u'c', u'd'], '//') self.checkmethod('split', 'a//b//c//d', [u'a', u'b', u'c', u'd'], u'//') self.checkmethod('split', u'endcase test', [u'endcase ', u''], u'test') self.checkmethod('split', u'endcase test', [u'endcase ', u''], 'test') self.checkmethod('split', 'endcase test', [u'endcase ', u''], u'test') self.assertRaises(TypeError, u"hello".split, 42, 42, 42) def test_join(self): class Sequence: def __init__(self, seq): self.seq = seq def __len__(self): return len(self.seq) def __getitem__(self, i): return self.seq[i] self.checkmethod('join', u' ', u'a b c d', [u'a', u'b', u'c', u'd']) self.checkmethod('join', u' ', u'a b c d', ['a', 'b', u'c', u'd']) self.checkmethod('join', u'', u'abcd', (u'a', u'b', u'c', u'd')) self.checkmethod('join', u' ', u'w x y z', Sequence('wxyz')) self.assertRaises(TypeError, u' '.join, 7) self.assertRaises(TypeError, u' '.join, Sequence([7, u'hello', 123L])) self.checkmethod('join', ' ', u'a b c d', [u'a', u'b', u'c', u'd']) self.checkmethod('join', ' ', u'a b c d', ['a', 'b', u'c', u'd']) self.checkmethod('join', '', u'abcd', (u'a', u'b', u'c', u'd')) self.checkmethod('join', ' ', u'w x y z', Sequence(u'wxyz')) self.assertRaises(TypeError, ' '.join, TypeError) result = u'' for i in range(10): if i > 0: result = result + u':' result = result + u'x'*10 self.checkmethod('join', u':', result, [u'x' * 10] * 10) self.checkmethod('join', u':', result, (u'x' * 10,) * 10) self.assertRaises(TypeError, u"hello".join) def test_strip(self): self.checkmethod('strip', u' hello ', u'hello') self.checkmethod('lstrip', u' hello ', u'hello ') self.checkmethod('rstrip', u' hello ', u' hello') self.checkmethod('strip', u'hello', u'hello') self.checkmethod('strip', u' hello ', u'hello', None) self.checkmethod('lstrip', u' hello ', u'hello ', None) self.checkmethod('rstrip', u' hello ', u' hello', None) self.checkmethod('strip', u'hello', u'hello', None) self.checkmethod('strip', u'xyzzyhelloxyzzy', u'hello', u'xyz') self.checkmethod('lstrip', u'xyzzyhelloxyzzy', u'helloxyzzy', u'xyz') self.checkmethod('rstrip', u'xyzzyhelloxyzzy', u'xyzzyhello', u'xyz') self.checkmethod('strip', u'hello', u'hello', u'xyz') self.checkmethod('strip', u'xyzzyhelloxyzzy', u'hello', 'xyz') self.checkmethod('lstrip', u'xyzzyhelloxyzzy', u'helloxyzzy', 'xyz') self.checkmethod('rstrip', u'xyzzyhelloxyzzy', u'xyzzyhello', 'xyz') self.checkmethod('strip', u'hello', u'hello', 'xyz') self.assertRaises(TypeError, u"hello".strip, 42, 42) self.assertRaises(UnicodeError, u"hello".strip, "\xff") def test_swapcase(self): self.checkmethod('swapcase', u'HeLLo cOmpUteRs', u'hEllO CoMPuTErS') self.assertRaises(TypeError, u"hello".swapcase, 42) def test_replace(self): self.checkmethod('replace', u'one!two!three!', u'one@two!three!', u'!', u'@', 1) self.checkmethod('replace', u'one!two!three!', u'onetwothree', '!', '') self.checkmethod('replace', u'one!two!three!', u'one@two@three!', u'!', u'@', 2) self.checkmethod('replace', u'one!two!three!', u'one@two@three@', u'!', u'@', 3) self.checkmethod('replace', u'one!two!three!', u'one@two@three@', u'!', u'@', 4) self.checkmethod('replace', u'one!two!three!', u'one!two!three!', u'!', u'@', 0) self.checkmethod('replace', u'one!two!three!', u'one@two@three@', u'!', u'@') self.checkmethod('replace', u'one!two!three!', u'one!two!three!', u'x', u'@') self.checkmethod('replace', u'one!two!three!', u'one!two!three!', u'x', u'@', 2) self.checkmethod('replace', u'abc', u'-a-b-c-', u'', u'-') self.checkmethod('replace', u'abc', u'-a-b-c', u'', u'-', 3) self.checkmethod('replace', u'abc', u'abc', u'', u'-', 0) self.checkmethod('replace', u'abc', u'abc', u'ab', u'--', 0) self.checkmethod('replace', u'abc', u'abc', u'xy', u'--') self.checkmethod('replace', u'', u'', u'', u'') self.checkmethod('replace', 'one!two!three!', u'one@two!three!', u'!', u'@', 1) self.assertRaises(TypeError, 'replace'.replace, 42) self.assertRaises(TypeError, 'replace'.replace, u"r", 42) self.assertRaises(TypeError, u"hello".replace) self.assertRaises(TypeError, u"hello".replace, 42, u"h") self.assertRaises(TypeError, u"hello".replace, u"h", 42) def test_startswith(self): self.checkmethod('startswith', u'hello', True, u'he') self.checkmethod('startswith', u'hello', True, u'hello') self.checkmethod('startswith', u'hello', False, u'hello world') self.checkmethod('startswith', u'hello', True, u'') self.checkmethod('startswith', u'hello', False, u'ello') self.checkmethod('startswith', u'hello', True, u'ello', 1) self.checkmethod('startswith', u'hello', True, u'o', 4) self.checkmethod('startswith', u'hello', False, u'o', 5) self.checkmethod('startswith', u'hello', True, u'', 5) self.checkmethod('startswith', u'hello', False, u'lo', 6) self.checkmethod('startswith', u'helloworld', True, u'lowo', 3) self.checkmethod('startswith', u'helloworld', True, u'lowo', 3, 7) self.checkmethod('startswith', u'helloworld', False, u'lowo', 3, 6) self.assertRaises(TypeError, u"hello".startswith) self.assertRaises(TypeError, u"hello".startswith, 42) def test_endswith(self): self.checkmethod('endswith', u'hello', True, u'lo') self.checkmethod('endswith', u'hello', False, u'he') self.checkmethod('endswith', u'hello', True, u'') self.checkmethod('endswith', u'hello', False, u'hello world') self.checkmethod('endswith', u'helloworld', False, u'worl') self.checkmethod('endswith', u'helloworld', True, u'worl', 3, 9) self.checkmethod('endswith', u'helloworld', True, u'world', 3, 12) self.checkmethod('endswith', u'helloworld', True, u'lowo', 1, 7) self.checkmethod('endswith', u'helloworld', True, u'lowo', 2, 7) self.checkmethod('endswith', u'helloworld', True, u'lowo', 3, 7) self.checkmethod('endswith', u'helloworld', False, u'lowo', 4, 7) self.checkmethod('endswith', u'helloworld', False, u'lowo', 3, 8) self.checkmethod('endswith', u'ab', False, u'ab', 0, 1) self.checkmethod('endswith', u'ab', False, u'ab', 0, 0) self.checkmethod('endswith', 'helloworld', True, u'd') self.checkmethod('endswith', 'helloworld', False, u'l') self.assertRaises(TypeError, u"hello".endswith) self.assertRaises(TypeError, u"hello".endswith, 42) def test_expandtabs(self): self.checkmethod('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab def\ng hi') self.checkmethod('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab def\ng hi', 8) self.checkmethod('expandtabs', u'abc\rab\tdef\ng\thi', u'abc\rab def\ng hi', 4) self.checkmethod('expandtabs', u'abc\r\nab\tdef\ng\thi', u'abc\r\nab def\ng hi', 4) self.checkmethod('expandtabs', u'abc\r\nab\r\ndef\ng\r\nhi', u'abc\r\nab\r\ndef\ng\r\nhi', 4) self.assertRaises(TypeError, u"hello".expandtabs, 42, 42) def test_capwords(self): if 0: self.checkmethod('capwords', u'abc def ghi', u'Abc Def Ghi') self.checkmethod('capwords', u'abc\tdef\nghi', u'Abc Def Ghi') self.checkmethod('capwords', u'abc\t def \nghi', u'Abc Def Ghi') def test_zfill(self): self.checkmethod('zfill', u'123', u'123', 2) self.checkmethod('zfill', u'123', u'123', 3) self.checkmethod('zfill', u'123', u'0123', 4) self.checkmethod('zfill', u'+123', u'+123', 3) self.checkmethod('zfill', u'+123', u'+123', 4) self.checkmethod('zfill', u'+123', u'+0123', 5) self.checkmethod('zfill', u'-123', u'-123', 3) self.checkmethod('zfill', u'-123', u'-123', 4) self.checkmethod('zfill', u'-123', u'-0123', 5) self.checkmethod('zfill', u'', u'000', 3) self.checkmethod('zfill', u'34', u'34', 1) self.checkmethod('zfill', u'34', u'00034', 5) self.assertRaises(TypeError, u"123".zfill) def test_comparison(self): self.assertEqual(u'abc', 'abc') self.assertEqual('abc', u'abc') self.assertEqual(u'abc', u'abc') self.assert_(u'abcd' > 'abc') self.assert_('abcd' > u'abc') self.assert_(u'abcd' > u'abc') self.assert_(u'abc' < 'abcd') self.assert_('abc' < u'abcd') self.assert_(u'abc' < u'abcd') if 0: self.assert_(u'\u0061' < u'\u20ac') self.assert_(u'\u0061' < u'\ud800\udc02') def test_lecmp(s, s2): self.assert_(s < s2) def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_lecmp(s, s2) s2 = u'\ud800\ude01' test_lecmp(s, s2) s2 = u'\ud900\ude01' test_lecmp(s, s2) s2 = u'\uda00\ude01' test_lecmp(s, s2) s2 = u'\udb00\ude01' test_lecmp(s, s2) s2 = u'\ud800\udfff' test_lecmp(s, s2) s2 = u'\ud900\udfff' test_lecmp(s, s2) s2 = u'\uda00\udfff' test_lecmp(s, s2) s2 = u'\udb00\udfff' test_lecmp(s, s2) test_fixup(u'\ue000') test_fixup(u'\uff61') self.assert_(u'\ud800\udc02' < u'\ud84d\udc56') def test_ljust(self): self.checkmethod('ljust', u'abc', u'abc ', 10) self.checkmethod('ljust', u'abc', u'abc ', 6) self.checkmethod('ljust', u'abc', u'abc', 2) self.assertRaises(TypeError, u"abc".ljust) def test_rjust(self): self.checkmethod('rjust', u'abc', u' abc', 10) self.checkmethod('rjust', u'abc', u' abc', 6) self.checkmethod('rjust', u'abc', u'abc', 2) self.assertRaises(TypeError, u"abc".rjust) def test_center(self): self.checkmethod('center', u'abc', u' abc ', 10) self.checkmethod('center', u'abc', u' abc ', 6) self.checkmethod('center', u'abc', u'abc', 2) self.assertRaises(TypeError, u"abc".center) def test_islower(self): self.checkmethod('islower', u'', False) self.checkmethod('islower', u'a', True) self.checkmethod('islower', u'A', False) self.checkmethod('islower', u'\n', False) self.checkmethod('islower', u'\u1FFc', False) self.checkmethod('islower', u'abc', True) self.checkmethod('islower', u'aBc', False) self.checkmethod('islower', u'abc\n', True) self.assertRaises(TypeError, u"abc".islower, 42) def test_isupper(self): self.checkmethod('isupper', u'', False) self.checkmethod('isupper', u'a', False) self.checkmethod('isupper', u'A', True) self.checkmethod('isupper', u'\n', False) if sys.platform[:4] != 'java': self.checkmethod('isupper', u'\u1FFc', False) self.checkmethod('isupper', u'ABC', True) self.checkmethod('isupper', u'AbC', False) self.checkmethod('isupper', u'ABC\n', True) self.assertRaises(TypeError, u"abc".isupper, 42) def test_istitle(self): self.checkmethod('istitle', u'', False) self.checkmethod('istitle', u'a', False) self.checkmethod('istitle', u'A', True) self.checkmethod('istitle', u'\n', False) self.checkmethod('istitle', u'\u1FFc', True) self.checkmethod('istitle', u'A Titlecased Line', True) self.checkmethod('istitle', u'A\nTitlecased Line', True) self.checkmethod('istitle', u'A Titlecased, Line', True) self.checkmethod('istitle', u'Greek \u1FFcitlecases ...', True) self.checkmethod('istitle', u'Not a capitalized String', False) self.checkmethod('istitle', u'Not\ta Titlecase String', False) self.checkmethod('istitle', u'Not--a Titlecase String', False) self.checkmethod('istitle', u'NOT', False) self.assertRaises(TypeError, u"abc".istitle, 42) def test_isspace(self): self.checkmethod('isspace', u'', False) self.checkmethod('isspace', u'a', False) self.checkmethod('isspace', u' ', True) self.checkmethod('isspace', u'\t', True) self.checkmethod('isspace', u'\r', True) self.checkmethod('isspace', u'\n', True) self.checkmethod('isspace', u' \t\r\n', True) self.checkmethod('isspace', u' \t\r\na', False) self.assertRaises(TypeError, u"abc".isspace, 42) def test_isalpha(self): self.checkmethod('isalpha', u'', False) self.checkmethod('isalpha', u'a', True) self.checkmethod('isalpha', u'A', True) self.checkmethod('isalpha', u'\n', False) self.checkmethod('isalpha', u'\u1FFc', True) self.checkmethod('isalpha', u'abc', True) self.checkmethod('isalpha', u'aBc123', False) self.checkmethod('isalpha', u'abc\n', False) self.assertRaises(TypeError, u"abc".isalpha, 42) def test_isalnum(self): self.checkmethod('isalnum', u'', False) self.checkmethod('isalnum', u'a', True) self.checkmethod('isalnum', u'A', True) self.checkmethod('isalnum', u'\n', False) self.checkmethod('isalnum', u'123abc456', True) self.checkmethod('isalnum', u'a1b3c', True) self.checkmethod('isalnum', u'aBc000 ', False) self.checkmethod('isalnum', u'abc\n', False) self.assertRaises(TypeError, u"abc".isalnum, 42) def test_isdecimal(self): self.checkmethod('isdecimal', u'', False) self.checkmethod('isdecimal', u'a', False) self.checkmethod('isdecimal', u'0', True) self.checkmethod('isdecimal', u'\u2460', False) self.checkmethod('isdecimal', u'\xbc', False) self.checkmethod('isdecimal', u'\u0660', True) self.checkmethod('isdecimal', u'0123456789', True) self.checkmethod('isdecimal', u'0123456789a', False) self.assertRaises(TypeError, u"abc".isdecimal, 42) def test_isdigit(self): self.checkmethod('isdigit', u'', False) self.checkmethod('isdigit', u'a', False) self.checkmethod('isdigit', u'0', True) self.checkmethod('isdigit', u'\u2460', True) self.checkmethod('isdigit', u'\xbc', False) self.checkmethod('isdigit', u'\u0660', True) self.checkmethod('isdigit', u'0123456789', True) self.checkmethod('isdigit', u'0123456789a', False) self.assertRaises(TypeError, u"abc".isdigit, 42) def test_isnumeric(self): self.checkmethod('isnumeric', u'', False) self.checkmethod('isnumeric', u'a', False) self.checkmethod('isnumeric', u'0', True) self.checkmethod('isnumeric', u'\u2460', True) self.checkmethod('isnumeric', u'\xbc', True) self.checkmethod('isnumeric', u'\u0660', True) self.checkmethod('isnumeric', u'0123456789', True) self.checkmethod('isnumeric', u'0123456789a', False) self.assertRaises(TypeError, u"abc".isnumeric, 42) def test_splitlines(self): self.checkmethod('splitlines', u"abc\ndef\n\rghi", [u'abc', u'def', u'', u'ghi']) self.checkmethod('splitlines', u"abc\ndef\n\r\nghi", [u'abc', u'def', u'', u'ghi']) self.checkmethod('splitlines', u"abc\ndef\r\nghi", [u'abc', u'def', u'ghi']) self.checkmethod('splitlines', u"abc\ndef\r\nghi\n", [u'abc', u'def', u'ghi']) self.checkmethod('splitlines', u"abc\ndef\r\nghi\n\r", [u'abc', u'def', u'ghi', u'']) self.checkmethod('splitlines', u"\nabc\ndef\r\nghi\n\r", [u'', u'abc', u'def', u'ghi', u'']) self.checkmethod('splitlines', u"\nabc\ndef\r\nghi\n\r", [u'\n', u'abc\n', u'def\r\n', u'ghi\n', u'\r'], True) self.assertRaises(TypeError, u"abc".splitlines, 42, 42) def test_contains(self): self.assert_('a' in u'abdb') self.assert_('a' in u'bdab') self.assert_('a' in u'bdaba') self.assert_('a' in u'bdba') self.assert_('a' in u'bdba') self.assert_(u'a' in u'bdba') self.assert_(u'a' not in u'bdb') self.assert_(u'a' not in 'bdb') self.assert_(u'a' in 'bdba') self.assert_(u'a' in ('a',1,None)) self.assert_(u'a' in (1,None,'a')) self.assert_(u'a' in (1,None,u'a')) self.assert_('a' in ('a',1,None)) self.assert_('a' in (1,None,'a')) self.assert_('a' in (1,None,u'a')) self.assert_('a' not in ('x',1,u'y')) self.assert_('a' not in ('x',1,None)) self.assert_(u'abcd' not in u'abcxxxx') self.assert_(u'ab' in u'abcd') self.assert_('ab' in u'abc') self.assert_(u'ab' in 'abc') self.assert_(u'ab' in (1,None,u'ab')) self.assert_(u'' in u'abc') self.assert_('' in u'abc') self.assertRaises(UnicodeError, 'g\xe2teau'.__contains__, u'\xe2') self.assert_(u'' in '') self.assert_('' in u'') self.assert_(u'' in u'') self.assert_(u'' in 'abc') self.assert_('' in u'abc') self.assert_(u'' in u'abc') self.assert_(u'\0' not in 'abc') self.assert_('\0' not in u'abc') self.assert_(u'\0' not in u'abc') self.assert_(u'\0' in '\0abc') self.assert_('\0' in u'\0abc') self.assert_(u'\0' in u'\0abc') self.assert_(u'\0' in 'abc\0') self.assert_('\0' in u'abc\0') self.assert_(u'\0' in u'abc\0') self.assert_(u'a' in '\0abc') self.assert_('a' in u'\0abc') self.assert_(u'a' in u'\0abc') self.assert_(u'asdf' in 'asdf') self.assert_('asdf' in u'asdf') self.assert_(u'asdf' in u'asdf') self.assert_(u'asdf' not in 'asd') self.assert_('asdf' not in u'asd') self.assert_(u'asdf' not in u'asd') self.assert_(u'asdf' not in '') self.assert_('asdf' not in u'') self.assert_(u'asdf' not in u'') self.assertRaises(TypeError, u"abc".__contains__) def test_formatting(self): self.assertEqual(u"%s, %s" % (u"abc", "abc"), u'abc, abc') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", 1, 2, 3), u'abc, abc, 1, 2.000000, 3.00') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", 1, -2, 3), u'abc, abc, 1, -2.000000, 3.00') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.5), u'abc, abc, -1, -2.000000, 3.50') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 3.57), u'abc, abc, -1, -2.000000, 3.57') self.assertEqual(u"%s, %s, %i, %f, %5.2f" % (u"abc", "abc", -1, -2, 1003.57), u'abc, abc, -1, -2.000000, 1003.57') self.assertEqual(u"%c" % (u"a",), u'a') self.assertEqual(u"%c" % ("a",), u'a') self.assertEqual(u"%c" % (34,), u'"') self.assertEqual(u"%c" % (36,), u'$') self.assertEqual(u"%d".__mod__(10), u'10') if not sys.platform.startswith('java'): self.assertEqual(u"%r, %r" % (u"abc", "abc"), u"u'abc', 'abc'") self.assertEqual(u"%(x)s, %(y)s" % {'x':u"abc", 'y':"def"}, u'abc, def') self.assertEqual(u"%(x)s, %()s" % {'x':u"abc", u'':"def"}, u'abc, def') for ordinal in (-100, 0x200000): self.assertRaises(ValueError, u"%c".__mod__, ordinal) for prec in xrange(100): format = u'%%.%if' % prec value = 0.01 for x in xrange(60): value = value * 3.141592655 / 3.0 * 10.0 if x < 50 and prec >= 67: self.assertRaises(OverflowError, format.__mod__, value) else: format % value self.assertEqual('...%(foo)s...' % {'foo':u"abc"}, u'...abc...') self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...') self.assertEqual('...%(foo)s...' % {u'foo':"abc"}, '...abc...') self.assertEqual('...%(foo)s...' % {u'foo':u"abc"}, u'...abc...') self.assertEqual('...%(foo)s...' % {u'foo':u"abc",'def':123}, u'...abc...') self.assertEqual('...%(foo)s...' % {u'foo':u"abc",u'def':123}, u'...abc...') self.assertEqual('...%s...%s...%s...%s...' % (1,2,3,u"abc"), u'...1...2...3...abc...') self.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,u"abc"), u'...%...%s...1...2...3...abc...') self.assertEqual('...%s...' % u"abc", u'...abc...') self.assertEqual('%*s' % (5,u'abc',), u' abc') self.assertEqual('%*s' % (-5,u'abc',), u'abc ') self.assertEqual('%*.*s' % (5,2,u'abc',), u' ab') self.assertEqual('%*.*s' % (5,3,u'abc',), u' abc') self.assertEqual('%i %*.*s' % (10, 5,3,u'abc',), u'10 abc') self.assertEqual('%i%s %*.*s' % (10, 3, 5,3,u'abc',), u'103 abc') self.assertEqual(u'%3ld' % 42, u' 42') self.assertEqual(u'%07.2f' % 42, u'0042.00') self.assertRaises(TypeError, u"abc".__mod__) self.assertRaises(TypeError, u"%(foo)s".__mod__, 42) self.assertRaises(TypeError, u"%s%s".__mod__, (42,)) self.assertRaises(TypeError, u"%c".__mod__, (None,)) self.assertRaises(ValueError, u"%c".__mod__, (sys.maxunicode+1,)) self.assertRaises(ValueError, u"%(foo".__mod__, {}) self.assertRaises(TypeError, u"%(foo)s %(bar)s".__mod__, (u"foo", 42)) self.assertEqual(u"%((foo))s" % {u"(foo)": u"bar"}, u"bar") self.assertEqual(u"%sx" % (103*u"a"), 103*u"a"+u"x") self.assertRaises(TypeError, u"%*s".__mod__, (u"foo", u"bar")) self.assertRaises(TypeError, u"%10.*f".__mod__, (u"foo", 42.)) self.assertRaises(ValueError, u"%10".__mod__, (42,)) def test_constructor(self): self.assertEqual( unicode(u'unicode remains unicode'), u'unicode remains unicode' ) class UnicodeSubclass(unicode): pass self.assertEqual( unicode(UnicodeSubclass('unicode subclass becomes unicode')), u'unicode subclass becomes unicode' ) self.assertEqual( unicode('strings are converted to unicode'), u'strings are converted to unicode' ) class UnicodeCompat: def __init__(self, x): self.x = x def __unicode__(self): return self.x self.assertEqual( unicode(UnicodeCompat('__unicode__ compatible objects are recognized')), u'__unicode__ compatible objects are recognized') class StringCompat: def __init__(self, x): self.x = x def __str__(self): return self.x self.assertEqual( unicode(StringCompat('__str__ compatible objects are recognized')), u'__str__ compatible objects are recognized' ) o = StringCompat('unicode(obj) is compatible to str()') self.assertEqual(unicode(o), u'unicode(obj) is compatible to str()') self.assertEqual(str(o), 'unicode(obj) is compatible to str()') for obj in (123, 123.45, 123L): self.assertEqual(unicode(obj), unicode(str(obj))) if not sys.platform.startswith('java'): self.assertRaises( TypeError, unicode, u'decoding unicode is not supported', 'utf-8', 'strict' ) self.assertEqual( unicode('strings are decoded to unicode', 'utf-8', 'strict'), u'strings are decoded to unicode' ) if not sys.platform.startswith('java'): self.assertEqual( unicode( buffer('character buffers are decoded to unicode'), 'utf-8', 'strict' ), u'character buffers are decoded to unicode' ) self.assertRaises(TypeError, unicode, 42, 42, 42) def test_codecs_utf7(self): utfTests = [ (u'A\u2262\u0391.', 'A+ImIDkQ.'), (u'Hi Mom -\u263a-!', 'Hi Mom -+Jjo--!'), (u'\u65E5\u672C\u8A9E', '+ZeVnLIqe-'), (u'Item 3 is \u00a31.', 'Item 3 is +AKM-1.'), (u'+', '+-'), (u'+-', '+--'), (u'+?', '+-?'), (u'\?', '+AFw?'), (u'+?', '+-?'), (ur'\\?', '+AFwAXA?'), (ur'\\\?', '+AFwAXABc?'), (ur'++--', '+-+---') ] for (x, y) in utfTests: self.assertEqual(x.encode('utf-7'), y) self.assertRaises(UnicodeError, unicode, '+3ADYAA-', 'utf-7') self.assertEqual(unicode('+3ADYAA-', 'utf-7', 'replace'), u'\ufffd') def test_codecs_utf8(self): self.assertEqual(u''.encode('utf-8'), '') self.assertEqual(u'\u20ac'.encode('utf-8'), '\xe2\x82\xac') self.assertEqual(u'\ud800\udc02'.encode('utf-8'), '\xf0\x90\x80\x82') self.assertEqual(u'\ud84d\udc56'.encode('utf-8'), '\xf0\xa3\x91\x96') self.assertEqual(u'\ud800'.encode('utf-8'), '\xed\xa0\x80') self.assertEqual(u'\udc00'.encode('utf-8'), '\xed\xb0\x80') self.assertEqual( (u'\ud800\udc02'*1000).encode('utf-8'), '\xf0\x90\x80\x82'*1000 ) self.assertEqual( u'\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f' u'\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00' u'\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c' u'\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067' u'\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das' u' Nunstuck git und'.encode('utf-8'), '\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81' '\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3' '\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe' '\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83' '\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8' '\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81' '\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81' '\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3' '\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf' '\xe3\x80\x8cWenn ist das Nunstuck git und' ) self.assertEqual(unicode('\xf0\xa3\x91\x96', 'utf-8'), u'\U00023456' ) self.assertEqual(unicode('\xf0\x90\x80\x82', 'utf-8'), u'\U00010002' ) self.assertEqual(unicode('\xe2\x82\xac', 'utf-8'), u'\u20ac' ) def test_codecs_errors(self): self.assertRaises(UnicodeError, u'Andr\202 x'.encode, 'ascii') self.assertRaises(UnicodeError, u'Andr\202 x'.encode, 'ascii','strict') self.assertEqual(u'Andr\202 x'.encode('ascii','ignore'), "Andr x") self.assertEqual(u'Andr\202 x'.encode('ascii','replace'), "Andr? x") self.assertRaises(UnicodeError, unicode, 'Andr\202 x', 'ascii') self.assertRaises(UnicodeError, unicode, 'Andr\202 x', 'ascii','strict') self.assertEqual(unicode('Andr\202 x','ascii','ignore'), u"Andr x") self.assertEqual(unicode('Andr\202 x','ascii','replace'), u'Andr\uFFFD x') self.assertEqual("\\N{foo}xx".decode("unicode-escape", "ignore"), u"xx") self.assertRaises(UnicodeError, "\\".decode, "unicode-escape") def search_function(encoding): def decode1(input, errors="strict"): return 42 def encode1(input, errors="strict"): return 42 def encode2(input, errors="strict"): return (42, 42) def decode2(input, errors="strict"): return (42, 42) if encoding=="test.unicode1": return (encode1, decode1, None, None) elif encoding=="test.unicode2": return (encode2, decode2, None, None)
def __repr__(self): return 'usub(%r)' % unicode.__repr__(self)
28256f276e1d61d54301b874958fc78c26117c9e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/28256f276e1d61d54301b874958fc78c26117c9e/test_unicode.py
return None codecs.register(search_function) self.assertRaises(TypeError, "hello".decode, "test.unicode1") self.assertRaises(TypeError, unicode, "hello", "test.unicode2") self.assertRaises(TypeError, u"hello".encode, "test.unicode1") self.assertRaises(TypeError, u"hello".encode, "test.unicode2") import imp self.assertRaises( ImportError, imp.find_module, "non-existing module", [u"non-existing dir"] ) self.assertRaises(TypeError, u"hello".encode, 42, 42, 42) self.assertRaises(UnicodeError, int, u"\u0200") def test_codecs(self): self.assertEqual(u'hello'.encode('ascii'), 'hello') self.assertEqual(u'hello'.encode('utf-7'), 'hello') self.assertEqual(u'hello'.encode('utf-8'), 'hello') self.assertEqual(u'hello'.encode('utf8'), 'hello') self.assertEqual(u'hello'.encode('utf-16-le'), 'h\000e\000l\000l\000o\000') self.assertEqual(u'hello'.encode('utf-16-be'), '\000h\000e\000l\000l\000o') self.assertEqual(u'hello'.encode('latin-1'), 'hello') u = u''.join(map(unichr, xrange(1024))) for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le', 'utf-16-be', 'raw_unicode_escape', 'unicode_escape', 'unicode_internal'): self.assertEqual(unicode(u.encode(encoding),encoding), u) u = u''.join(map(unichr, xrange(256))) for encoding in ('latin-1',): self.assertEqual(unicode(u.encode(encoding),encoding), u) u = u''.join(map(unichr, xrange(128))) for encoding in ('ascii',): self.assertEqual(unicode(u.encode(encoding),encoding), u) u = u'\U00010001\U00020002\U00030003\U00040004\U00050005' for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be', 'unicode_escape', 'unicode_internal'): self.assertEqual(unicode(u.encode(encoding),encoding), u) u = u''.join(map(unichr, range(0,0xd800)+range(0xe000,0x10000))) for encoding in ('utf-8',): self.assertEqual(unicode(u.encode(encoding),encoding), u) def test_codecs_charmap(self): s = ''.join(map(chr, xrange(128))) for encoding in ( 'cp037', 'cp1026', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp860', 'cp861', 'cp862', 'cp863', 'cp865', 'cp866', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_9', 'koi8_r', 'latin_1', 'mac_cyrillic', 'mac_latin2', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874', 'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish', 'cp1006', 'iso8859_8', ): self.assertEqual(unicode(s, encoding).encode(encoding), s) s = ''.join(map(chr, xrange(128, 256))) for encoding in ( 'cp037', 'cp1026', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp860', 'cp861', 'cp862', 'cp863', 'cp865', 'cp866', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_2', 'iso8859_4', 'iso8859_5', 'iso8859_9', 'koi8_r', 'latin_1', 'mac_cyrillic', 'mac_latin2', ): self.assertEqual(unicode(s, encoding).encode(encoding), s) def test_concatenation(self): self.assertEqual((u"abc" u"def"), u"abcdef") self.assertEqual(("abc" u"def"), u"abcdef") self.assertEqual((u"abc" "def"), u"abcdef") self.assertEqual((u"abc" u"def" "ghi"), u"abcdefghi") self.assertEqual(("abc" "def" u"ghi"), u"abcdefghi") def test_printing(self): class BitBucket: def write(self, text):
def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_lecmp(s, s2) s2 = u'\ud800\ude01' test_lecmp(s, s2) s2 = u'\ud900\ude01' test_lecmp(s, s2) s2 = u'\uda00\ude01' test_lecmp(s, s2) s2 = u'\udb00\ude01' test_lecmp(s, s2) s2 = u'\ud800\udfff' test_lecmp(s, s2) s2 = u'\ud900\udfff' test_lecmp(s, s2) s2 = u'\uda00\udfff' test_lecmp(s, s2) s2 = u'\udb00\udfff' test_lecmp(s, s2)
28256f276e1d61d54301b874958fc78c26117c9e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/28256f276e1d61d54301b874958fc78c26117c9e/test_unicode.py
else: pass verify('...%(foo)s...' % {'foo':u"abc"} == u'...abc...') verify('...%(foo)s...' % {'foo':"abc"} == '...abc...') verify('...%(foo)s...' % {u'foo':"abc"} == '...abc...') verify('...%(foo)s...' % {u'foo':u"abc"} == u'...abc...') verify('...%(foo)s...' % {u'foo':u"abc",'def':123} == u'...abc...') verify('...%(foo)s...' % {u'foo':u"abc",u'def':123} == u'...abc...') verify('...%s...%s...%s...%s...' % (1,2,3,u"abc") == u'...1...2...3...abc...') verify('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,u"abc") == u'...%...%s...1...2...3...abc...') verify('...%s...' % u"abc" == u'...abc...') verify('%*s' % (5,u'abc',) == u' abc') verify('%*s' % (-5,u'abc',) == u'abc ') verify('%*.*s' % (5,2,u'abc',) == u' ab') verify('%*.*s' % (5,3,u'abc',) == u' abc') verify('%i %*.*s' % (10, 5,3,u'abc',) == u'10 abc') verify('%i%s %*.*s' % (10, 3, 5,3,u'abc',) == u'103 abc') print 'done.' print 'Testing builtin unicode()...', verify(unicode(u'unicode remains unicode') == u'unicode remains unicode') class UnicodeSubclass(unicode): pass verify(unicode(UnicodeSubclass('unicode subclass becomes unicode')) == u'unicode subclass becomes unicode') verify(unicode('strings are converted to unicode') == u'strings are converted to unicode') class UnicodeCompat: def __init__(self, x): self.x = x def __unicode__(self): return self.x verify(unicode(UnicodeCompat('__unicode__ compatible objects are recognized')) == u'__unicode__ compatible objects are recognized') class StringCompat: def __init__(self, x): self.x = x def __str__(self): return self.x verify(unicode(StringCompat('__str__ compatible objects are recognized')) == u'__str__ compatible objects are recognized') o = StringCompat('unicode(obj) is compatible to str()') verify(unicode(o) == u'unicode(obj) is compatible to str()') verify(str(o) == 'unicode(obj) is compatible to str()') for obj in (123, 123.45, 123L): verify(unicode(obj) == unicode(str(obj))) if not sys.platform.startswith('java'): try: unicode(u'decoding unicode is not supported', 'utf-8', 'strict') except TypeError: pass else: raise TestFailed, "decoding unicode should NOT be supported" verify(unicode('strings are decoded to unicode', 'utf-8', 'strict') == u'strings are decoded to unicode') if not sys.platform.startswith('java'): verify(unicode(buffer('character buffers are decoded to unicode'), 'utf-8', 'strict') == u'character buffers are decoded to unicode') print 'done.' print 'Testing builtin codecs...', utfTests = [(u'A\u2262\u0391.', 'A+ImIDkQ.'), (u'Hi Mom -\u263a-!', 'Hi Mom -+Jjo--!'), (u'\u65E5\u672C\u8A9E', '+ZeVnLIqe-'), (u'Item 3 is \u00a31.', 'Item 3 is +AKM-1.'), (u'+', '+-'), (u'+-', '+--'), (u'+?', '+-?'), (u'\?', '+AFw?'), (u'+?', '+-?'), (ur'\\?', '+AFwAXA?'), (ur'\\\?', '+AFwAXABc?'), (ur'++--', '+-+---')] for x,y in utfTests: verify( x.encode('utf-7') == y ) try: unicode('+3ADYAA-', 'utf-7') except UnicodeError: pass else: raise TestFailed, "unicode('+3ADYAA-', 'utf-7') failed to raise an exception" verify(unicode('+3ADYAA-', 'utf-7', 'replace') == u'\ufffd') verify(u''.encode('utf-8') == '') verify(u'\u20ac'.encode('utf-8') == '\xe2\x82\xac') verify(u'\ud800\udc02'.encode('utf-8') == '\xf0\x90\x80\x82') verify(u'\ud84d\udc56'.encode('utf-8') == '\xf0\xa3\x91\x96') verify(u'\ud800'.encode('utf-8') == '\xed\xa0\x80') verify(u'\udc00'.encode('utf-8') == '\xed\xb0\x80') verify((u'\ud800\udc02'*1000).encode('utf-8') == '\xf0\x90\x80\x82'*1000) verify(u'\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f' u'\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00' u'\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c' u'\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067' u'\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das' u' Nunstuck git und'.encode('utf-8') == '\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81' '\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3' '\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe' '\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83' '\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8' '\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81' '\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81' '\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3' '\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf' '\xe3\x80\x8cWenn ist das Nunstuck git und') verify(unicode('\xf0\xa3\x91\x96', 'utf-8') == u'\U00023456' ) verify(unicode('\xf0\x90\x80\x82', 'utf-8') == u'\U00010002' ) verify(unicode('\xe2\x82\xac', 'utf-8') == u'\u20ac' ) verify(unicode('hello','ascii') == u'hello') verify(unicode('hello','utf-8') == u'hello') verify(unicode('hello','utf8') == u'hello') verify(unicode('hello','latin-1') == u'hello') try: u'Andr\202 x'.encode('ascii') u'Andr\202 x'.encode('ascii','strict') except ValueError: pass else: raise TestFailed, "u'Andr\202'.encode('ascii') failed to raise an exception" verify(u'Andr\202 x'.encode('ascii','ignore') == "Andr x") verify(u'Andr\202 x'.encode('ascii','replace') == "Andr? x") try: unicode('Andr\202 x','ascii') unicode('Andr\202 x','ascii','strict') except ValueError: pass else: raise TestFailed, "unicode('Andr\202') failed to raise an exception" verify(unicode('Andr\202 x','ascii','ignore') == u"Andr x") verify(unicode('Andr\202 x','ascii','replace') == u'Andr\uFFFD x') verify("\\N{foo}xx".decode("unicode-escape", "ignore") == u"xx") try: "\\".decode("unicode-escape") except ValueError: pass else: raise TestFailed, '"\\".decode("unicode-escape") should fail' try: int(u"\u0200") except UnicodeError: pass else: raise TestFailed, "int(u'\\u0200') failed to raise an exception" verify(u'hello'.encode('ascii') == 'hello') verify(u'hello'.encode('utf-7') == 'hello') verify(u'hello'.encode('utf-8') == 'hello') verify(u'hello'.encode('utf8') == 'hello') verify(u'hello'.encode('utf-16-le') == 'h\000e\000l\000l\000o\000') verify(u'hello'.encode('utf-16-be') == '\000h\000e\000l\000l\000o') verify(u'hello'.encode('latin-1') == 'hello') u = u''.join(map(unichr, range(1024))) for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le', 'utf-16-be', 'raw_unicode_escape', 'unicode_escape', 'unicode_internal'): verify(unicode(u.encode(encoding),encoding) == u) u = u''.join(map(unichr, range(256))) for encoding in ( 'latin-1', ): try: verify(unicode(u.encode(encoding),encoding) == u) except TestFailed: print '*** codec "%s" failed round-trip' % encoding except ValueError,why: print '*** codec for "%s" failed: %s' % (encoding, why) u = u''.join(map(unichr, range(128))) for encoding in ( 'ascii', ): try: verify(unicode(u.encode(encoding),encoding) == u) except TestFailed: print '*** codec "%s" failed round-trip' % encoding except ValueError,why: print '*** codec for "%s" failed: %s' % (encoding, why) u = u'\U00010001\U00020002\U00030003\U00040004\U00050005' for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be', 'unicode_escape', 'unicode_internal'): verify(unicode(u.encode(encoding),encoding) == u) u = u''.join(map(unichr, range(0,0xd800)+range(0xe000,0x10000))) for encoding in ('utf-8',): verify(unicode(u.encode(encoding),encoding) == u) print 'done.' print 'Testing standard mapping codecs...', print '0-127...', s = ''.join(map(chr, range(128))) for encoding in ( 'cp037', 'cp1026', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp860', 'cp861', 'cp862', 'cp863', 'cp865', 'cp866', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6', 'iso8859_7', 'iso8859_9', 'koi8_r', 'latin_1', 'mac_cyrillic', 'mac_latin2', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874', 'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish', 'cp1006', 'iso8859_8', ): try: verify(unicode(s,encoding).encode(encoding) == s) except TestFailed: print '*** codec "%s" failed round-trip' % encoding except ValueError,why: print '*** codec for "%s" failed: %s' % (encoding, why) print '128-255...', s = ''.join(map(chr, range(128,256))) for encoding in ( 'cp037', 'cp1026', 'cp437', 'cp500', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp860', 'cp861', 'cp862', 'cp863', 'cp865', 'cp866', 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15', 'iso8859_2', 'iso8859_4', 'iso8859_5', 'iso8859_9', 'koi8_r', 'latin_1', 'mac_cyrillic', 'mac_latin2', ): try: verify(unicode(s,encoding).encode(encoding) == s) except TestFailed: print '*** codec "%s" failed round-trip' % encoding except ValueError,why: print '*** codec for "%s" failed: %s' % (encoding, why) print 'done.' print 'Testing Unicode string concatenation...', verify((u"abc" u"def") == u"abcdef") verify(("abc" u"def") == u"abcdef") verify((u"abc" "def") == u"abcdef") verify((u"abc" u"def" "ghi") == u"abcdefghi") verify(("abc" "def" u"ghi") == u"abcdefghi") print 'done.' print 'Testing Unicode printing...', print u'abc' print u'abc', u'def' print u'abc', 'def' print 'abc', u'def' print u'abc\n' print u'abc\n', print u'abc\n', print u'def\n' print u'def\n' print 'done.' def test_exception(lhs, rhs, msg): try: lhs in rhs except TypeError: pass else: raise TestFailed, msg def run_contains_tests(): vereq(u'' in '', True) vereq('' in u'', True) vereq(u'' in u'', True) vereq(u'' in 'abc', True) vereq('' in u'abc', True) vereq(u'' in u'abc', True) vereq(u'\0' in 'abc', False) vereq('\0' in u'abc', False) vereq(u'\0' in u'abc', False) vereq(u'\0' in '\0abc', True) vereq('\0' in u'\0abc', True) vereq(u'\0' in u'\0abc', True) vereq(u'\0' in 'abc\0', True) vereq('\0' in u'abc\0', True) vereq(u'\0' in u'abc\0', True) vereq(u'a' in '\0abc', True) vereq('a' in u'\0abc', True) vereq(u'a' in u'\0abc', True) vereq(u'asdf' in 'asdf', True) vereq('asdf' in u'asdf', True) vereq(u'asdf' in u'asdf', True) vereq(u'asdf' in 'asd', False) vereq('asdf' in u'asd', False) vereq(u'asdf' in u'asd', False) vereq(u'asdf' in '', False) vereq('asdf' in u'', False) vereq(u'asdf' in u'', False) run_contains_tests()
out = BitBucket() print >>out, u'abc' print >>out, u'abc', u'def' print >>out, u'abc', 'def' print >>out, 'abc', u'def' print >>out, u'abc\n' print >>out, u'abc\n', print >>out, u'abc\n', print >>out, u'def\n' print >>out, u'def\n' def test_mul(self): self.checkmethod('__mul__', u'abc', u'', -1) self.checkmethod('__mul__', u'abc', u'', 0) self.checkmethod('__mul__', u'abc', u'abc', 1) self.checkmethod('__mul__', u'abc', u'abcabcabc', 3) self.assertRaises(OverflowError, (10000*u'abc').__mul__, sys.maxint) def test_subscript(self): self.checkmethod('__getitem__', u'abc', u'a', 0) self.checkmethod('__getitem__', u'abc', u'c', -1) self.checkmethod('__getitem__', u'abc', u'a', 0L) self.checkmethod('__getitem__', u'abc', u'abc', slice(0, 3)) self.checkmethod('__getitem__', u'abc', u'abc', slice(0, 1000)) self.checkmethod('__getitem__', u'abc', u'a', slice(0, 1)) self.checkmethod('__getitem__', u'abc', u'', slice(0, 0)) self.assertRaises(TypeError, u"abc".__getitem__, "def") def test_slice(self): self.checkmethod('__getslice__', u'abc', u'abc', 0, 1000) self.checkmethod('__getslice__', u'abc', u'abc', 0, 3) self.checkmethod('__getslice__', u'abc', u'ab', 0, 2) self.checkmethod('__getslice__', u'abc', u'bc', 1, 3) self.checkmethod('__getslice__', u'abc', u'b', 1, 2) self.checkmethod('__getslice__', u'abc', u'', 2, 2) self.checkmethod('__getslice__', u'abc', u'', 1000, 1000) self.checkmethod('__getslice__', u'abc', u'', 2000, 1000) self.checkmethod('__getslice__', u'abc', u'', 2, 1) def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(UnicodeTest)) test.test_support.run_suite(suite) if __name__ == "__main__": test_main()
def test_fixup(s): s2 = u'\ud800\udc01' test_lecmp(s, s2) s2 = u'\ud900\udc01' test_lecmp(s, s2) s2 = u'\uda00\udc01' test_lecmp(s, s2) s2 = u'\udb00\udc01' test_lecmp(s, s2) s2 = u'\ud800\udd01' test_lecmp(s, s2) s2 = u'\ud900\udd01' test_lecmp(s, s2) s2 = u'\uda00\udd01' test_lecmp(s, s2) s2 = u'\udb00\udd01' test_lecmp(s, s2) s2 = u'\ud800\ude01' test_lecmp(s, s2) s2 = u'\ud900\ude01' test_lecmp(s, s2) s2 = u'\uda00\ude01' test_lecmp(s, s2) s2 = u'\udb00\ude01' test_lecmp(s, s2) s2 = u'\ud800\udfff' test_lecmp(s, s2) s2 = u'\ud900\udfff' test_lecmp(s, s2) s2 = u'\uda00\udfff' test_lecmp(s, s2) s2 = u'\udb00\udfff' test_lecmp(s, s2)
28256f276e1d61d54301b874958fc78c26117c9e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/28256f276e1d61d54301b874958fc78c26117c9e/test_unicode.py
print dir(tas)
print fixdir(dir(tas))
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
d304f44906b818c7e336fcbb99241516c9170d29 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/d304f44906b818c7e336fcbb99241516c9170d29/test_pkg.py
print dir(subpar)
print fixdir(dir(subpar))
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
d304f44906b818c7e336fcbb99241516c9170d29 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/d304f44906b818c7e336fcbb99241516c9170d29/test_pkg.py
print dir(subsubsub)
print fixdir(dir(subsubsub))
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc(file=sys.stdout) finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
d304f44906b818c7e336fcbb99241516c9170d29 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/8546/d304f44906b818c7e336fcbb99241516c9170d29/test_pkg.py