make all syntax compatible with 3.1 and 2.5

--HG--
branch : trunk
This commit is contained in:
Benjamin Peterson 2009-08-29 13:04:48 -05:00
parent 6f4c6d36a4
commit ee1747fcb4
60 changed files with 230 additions and 177 deletions

View File

@ -85,7 +85,7 @@ def test_importall():
yield check_import, modpath yield check_import, modpath
def check_import(modpath): def check_import(modpath):
print "checking import", modpath py.builtin.print_("checking import", modpath)
assert __import__(modpath) assert __import__(modpath)
# #

View File

@ -25,7 +25,7 @@ def test_invoke_compile(recwarn, monkeypatch):
return 1 return 1
\n""", '', 'exec') \n""", '', 'exec')
d = {} d = {}
exec co in d py.builtin.exec_(co, d)
assert py.code.Source(d['f']) assert py.code.Source(d['f'])
finally: finally:
py.magic.revoke(compile=True) py.magic.revoke(compile=True)
@ -100,12 +100,12 @@ class Testautopath:
d = {'__file__' : str(testpath)} d = {'__file__' : str(testpath)}
oldsyspath = sys.path[:] oldsyspath = sys.path[:]
try: try:
exec self.getauto in d py.test.exec_(self.getauto, d)
conf = d['autopath'] conf = d['autopath']
assert conf.dirpath() == self.initdir2 assert conf.dirpath() == self.initdir2
assert conf.pkgdir == self.initdir assert conf.pkgdir == self.initdir
assert str(self.root) in sys.path assert str(self.root) in sys.path
exec self.getauto in d py.test.exec_(self.getauto in d)
assert conf is not d['autopath'] assert conf is not d['autopath']
finally: finally:
sys.path[:] = oldsyspath sys.path[:] = oldsyspath
@ -116,12 +116,12 @@ class Testautopath:
d = {'__file__' : str(testpath)} d = {'__file__' : str(testpath)}
oldsyspath = sys.path[:] oldsyspath = sys.path[:]
try: try:
exec self.getauto in d py.test.exec_(self.getauto, d)
conf = d['autopath'] conf = d['autopath']
assert conf == self.initdir2.join('autoconfiguretest.py') assert conf == self.initdir2.join('autoconfiguretest.py')
assert conf.pkgdir == self.initdir assert conf.pkgdir == self.initdir
assert str(self.root) in sys.path assert str(self.root) in sys.path
exec self.getauto in d py.test.exec_(self.getauto, d)
assert conf is not d['autopath'] assert conf is not d['autopath']
finally: finally:
sys.path[:] = oldsyspath sys.path[:] = oldsyspath
@ -131,13 +131,13 @@ class Testautopath:
d = {'__file__' : str(testpath)} d = {'__file__' : str(testpath)}
oldsyspath = sys.path[:] oldsyspath = sys.path[:]
try: try:
exec self.getauto in d py.test.exec_(self.getauto, d)
conf = d['autopath'] conf = d['autopath']
assert conf.dirpath() == self.root assert conf.dirpath() == self.root
assert conf.pkgdir == self.root assert conf.pkgdir == self.root
syspath = sys.path[:] syspath = sys.path[:]
assert str(self.root) in syspath assert str(self.root) in syspath
exec self.getauto in d py.test.exec_(self.getauto, d)
assert conf is not d['autopath'] assert conf is not d['autopath']
finally: finally:
sys.path[:] = oldsyspath sys.path[:] = oldsyspath
@ -149,7 +149,7 @@ class Testautopath:
oldsyspath = sys.path[:] oldsyspath = sys.path[:]
try: try:
d = {} d = {}
exec self.getauto in d py.test.exec_(self.getauto, d)
conf = d['autopath'] conf = d['autopath']
assert conf.dirpath() == self.initdir2 assert conf.dirpath() == self.initdir2
assert conf.pkgdir == self.initdir assert conf.pkgdir == self.initdir
@ -167,7 +167,7 @@ class Testautopath:
try: try:
py.test.raises(ValueError,''' py.test.raises(ValueError,'''
d = {} d = {}
exec self.getauto in d py.test.exec_(self.getauto, d)
''') ''')
finally: finally:
sys.path[:] = oldsyspath sys.path[:] = oldsyspath

View File

@ -29,5 +29,5 @@ def setenv(name, value):
assert False, 'Shell not supported.' assert False, 'Shell not supported.'
return cmd return cmd
print prepend_path('PATH', bindir) print(prepend_path('PATH', bindir))
print prepend_path('PYTHONPATH', rootdir) print(prepend_path('PYTHONPATH', rootdir))

View File

@ -27,10 +27,10 @@ def main():
for arg in args: for arg in args:
path = py.path.local(arg) path = py.path.local(arg)
print "cleaning path", path, "of extensions", ext py.builtin.print_("cleaning path", path, "of extensions", ext)
for x in path.visit(shouldremove, lambda x: x.check(dotfile=0, link=0)): for x in path.visit(shouldremove, lambda x: x.check(dotfile=0, link=0)):
if options.dryrun: if options.dryrun:
print "would remove", x py.builtin.print_("would remove", x)
else: else:
print "removing", x py.builtin.print_("removing", x)
x.remove() x.remove()

View File

@ -85,10 +85,10 @@ def countloc(paths=None):
items = counter.file2numlines.items() items = counter.file2numlines.items()
items.sort(lambda x,y: cmp(x[1], y[1])) items.sort(lambda x,y: cmp(x[1], y[1]))
for x, y in items: for x, y in items:
print "%3d %30s" % (y,x) print("%3d %30s" % (y,x))
print "%30s %3d" %("number of testfiles", numtestfiles) print("%30s %3d" %("number of testfiles", numtestfiles))
print "%30s %3d" %("number of non-empty testlines", numtestlines) print("%30s %3d" %("number of non-empty testlines", numtestlines))
print "%30s %3d" %("number of files", numfiles) print("%30s %3d" %("number of files", numfiles))
print "%30s %3d" %("number of non-empty lines", numlines) print("%30s %3d" %("number of non-empty lines", numlines))

View File

@ -44,7 +44,7 @@ def main():
if options.ignorecase: if options.ignorecase:
s = s.lower() s = s.lower()
if s.find(string) != -1: if s.find(string) != -1:
print >>sys.stdout, "%s: filename matches %r" %(x, string) sys.stdout.write("%s: filename matches %r" %(x, string) + "\n")
try: try:
s = x.read() s = x.read()
@ -75,5 +75,5 @@ def main():
else: else:
context = (options.context)/2 context = (options.context)/2
for count in range(max(0, i-context), min(len(lines) - 1, i+context+1)): for count in range(max(0, i-context), min(len(lines) - 1, i+context+1)):
print "%s:%d: %s" %(x.relto(curdir), count+1, lines[count].rstrip()) print("%s:%d: %s" %(x.relto(curdir), count+1, lines[count].rstrip()))
print "-" * terminal_width print("-" * terminal_width)

View File

@ -17,7 +17,7 @@ import py
if hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()): if hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()):
def log(msg): def log(msg):
print msg print(msg)
else: else:
def log(msg): def log(msg):
pass pass
@ -37,8 +37,9 @@ def main():
try: try:
from py.__.rest import directive, resthtml from py.__.rest import directive, resthtml
from py.__.rest.latex import process_rest_file, process_configfile from py.__.rest.latex import process_rest_file, process_configfile
except ImportError, e: except ImportError:
print str(e) e = sys.exc_info()[1]
print(str(e))
sys.exit(1) sys.exit(1)
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
@ -70,7 +71,7 @@ def main():
if options.topdf: if options.topdf:
cfg = p.new(ext=".rst2pdfconfig") cfg = p.new(ext=".rst2pdfconfig")
if cfg.check(): if cfg.check():
print "using config file %s" % (cfg, ) print("using config file %s" % (cfg, ))
process_configfile(cfg, options.debug) process_configfile(cfg, options.debug)
else: else:
process_rest_file(p.localpath, process_rest_file(p.localpath,

View File

@ -19,7 +19,7 @@ the following 'svn up' won't just crash.
import sys, py import sys, py
def kill(p, root): def kill(p, root):
print '< %s' % (p.relto(root),) print('< %s' % (p.relto(root),))
p.remove(rec=1) p.remove(rec=1)
def svnwcrevert(path, root=None, precious=[]): def svnwcrevert(path, root=None, precious=[]):

View File

@ -13,11 +13,11 @@ def main():
try: try:
mod = __import__(name) mod = __import__(name)
except ImportError: except ImportError:
print >>sys.stderr, "could not import:", name sys.stderr.write("could not import: " + name + "\n")
else: else:
try: try:
location = mod.__file__ location = mod.__file__
except AttributeError: except AttributeError:
print >>sys.stderr, "module (has no __file__):", mod sys.stderr.write("module (has no __file__): " + mod)
else: else:
print location print(location)

View File

@ -26,19 +26,20 @@ def checkprocess(script):
cmd = "%s" %(script, ) cmd = "%s" %(script, )
# XXX distributed testing's rsync does not support # XXX distributed testing's rsync does not support
# syncing executable bits # syncing executable bits
script.chmod(0777) script.chmod(int("777", 8))
if script.basename.startswith("py.lookup") or \ if script.basename.startswith("py.lookup") or \
script.basename.startswith("py.which"): script.basename.startswith("py.which"):
cmd += " sys" cmd += " sys"
print "executing", script py.builtin.print_("executing", script)
try: try:
old = script.dirpath().chdir() old = script.dirpath().chdir()
try: try:
py.process.cmdexec(cmd) py.process.cmdexec(cmd)
finally: finally:
old.chdir() old.chdir()
except py.process.cmdexec.Error, e: except py.process.cmdexec.Error:
e = sys.exc_info()[1]
if cmd.find("py.rest") != -1 and \ if cmd.find("py.rest") != -1 and \
e.out.find("module named") != -1: e.out.find("module named") != -1:
return return

View File

@ -53,7 +53,7 @@ def revert(namespace, name):
) )
nref = (namespace, name) nref = (namespace, name)
if nref not in patched or not patched[nref]: if nref not in patched or not patched[nref]:
raise ValueError, "No original value stored for %s.%s" % nref raise ValueError("No original value stored for %s.%s" % nref)
current = getattr(namespace, name) current = getattr(namespace, name)
orig = patched[nref].pop() orig = patched[nref].pop()
setattr(namespace, name, orig) setattr(namespace, name, orig)

View File

@ -144,7 +144,7 @@ class Channel(object):
""" """
self._receiveclosed.wait(timeout=timeout) # wait for non-"opened" state self._receiveclosed.wait(timeout=timeout) # wait for non-"opened" state
if not self._receiveclosed.isSet(): if not self._receiveclosed.isSet():
raise IOError, "Timeout" raise IOError("Timeout")
error = self._getremoteerror() error = self._getremoteerror()
if error: if error:
raise error raise error
@ -155,7 +155,7 @@ class Channel(object):
Note that an item needs to be marshallable. Note that an item needs to be marshallable.
""" """
if self.isclosed(): if self.isclosed():
raise IOError, "cannot send to %r" %(self,) raise IOError("cannot send to %r" %(self,))
if isinstance(item, Channel): if isinstance(item, Channel):
data = Message.CHANNEL_NEW(self.id, item.id) data = Message.CHANNEL_NEW(self.id, item.id)
else: else:

View File

@ -237,7 +237,7 @@ class Gateway(object):
try: try:
co = compile(source+'\n', '', 'exec', co = compile(source+'\n', '', 'exec',
__future__.CO_GENERATOR_ALLOWED) __future__.CO_GENERATOR_ALLOWED)
exec co in loc py.test.exec_(co, loc)
finally: finally:
close() close()
self._trace("execution finished:", repr(source)[:50]) self._trace("execution finished:", repr(source)[:50])

View File

@ -123,4 +123,5 @@ class HostRSync(py.execnet.RSync):
if self._verbose: if self._verbose:
path = os.path.basename(self._sourcedir) + "/" + modified_rel_path path = os.path.basename(self._sourcedir) + "/" + modified_rel_path
remotepath = gateway.spec.chdir remotepath = gateway.spec.chdir
print '%s:%s <= %s' % (gateway.remoteaddress, remotepath, path) py.builtin.print_('%s:%s <= %s' %
(gateway.remoteaddress, remotepath, path))

View File

@ -14,8 +14,9 @@ class SocketIO:
try: try:
sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
sock.setsockopt(socket.SOL_IP, socket.IP_TOS, 0x10) # IPTOS_LOWDELAY sock.setsockopt(socket.SOL_IP, socket.IP_TOS, 0x10) # IPTOS_LOWDELAY
except socket.error, e: except socket.error:
print "WARNING: Cannot set socket option:", str(e) e = sys.exc_info()[1]
py.builtin.print_("WARNING: Cannot set socket option:", str(e))
self.readable = self.writeable = True self.readable = self.writeable = True
def read(self, numbytes): def read(self, numbytes):

View File

@ -63,6 +63,6 @@ class MultiChannel:
if first is None: if first is None:
first = py.std.sys.exc_info() first = py.std.sys.exc_info()
if first: if first:
raise first[0], first[1], first[2] py.builtin._reraise(first[0], first[1], first[2])

View File

@ -88,7 +88,8 @@ class RSync(object):
def _report_send_file(self, gateway, modified_rel_path): def _report_send_file(self, gateway, modified_rel_path):
if self._verbose: if self._verbose:
print '%s <= %s' % (gateway.remoteaddress, modified_rel_path) py.builtin.print_('%s <= %s' % (gateway.remoteaddress,
modified_rel_path))
def send(self, raises=True): def send(self, raises=True):
""" Sends a sourcedir to all added targets. Flag indicates """ Sends a sourcedir to all added targets. Flag indicates
@ -194,7 +195,7 @@ class RSync(object):
elif stat.S_ISLNK(st.st_mode): elif stat.S_ISLNK(st.st_mode):
self._send_link_structure(path) self._send_link_structure(path)
else: else:
raise ValueError, "cannot sync %r" % (path,) raise ValueError("cannot sync %r" % (path,))
REMOTE_SOURCE = py.path.local(__file__).dirpath().\ REMOTE_SOURCE = py.path.local(__file__).dirpath().\
join('rsync_remote.py').open().read() + "\nf()" join('rsync_remote.py').open().read() + "\nf()"

View File

@ -8,6 +8,7 @@ if __name__ == '__main__':
while 1: while 1:
cmdlist = ["python", script] cmdlist = ["python", script]
cmdlist.extend(sys.argv[1:]) cmdlist.extend(sys.argv[1:])
print "starting subcommand:", " ".join(cmdlist) text = "starting subcommand: " + " ".join(cmdlist)
print(text)
process = subprocess.Popen(cmdlist) process = subprocess.Popen(cmdlist)
process.wait() process.wait()

View File

@ -9,7 +9,7 @@ import sys, os, socket, select
try: try:
clientsock clientsock
except NameError: except NameError:
print "client side starting" print("client side starting")
import sys import sys
host, port = sys.argv[1].split(':') host, port = sys.argv[1].split(':')
port = int(port) port = int(port)
@ -17,7 +17,7 @@ except NameError:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port)) sock.connect((host, port))
sock.sendall(repr(myself)+'\n') sock.sendall(repr(myself)+'\n')
print "send boot string" print("send boot string")
inputlist = [ sock, sys.stdin ] inputlist = [ sock, sys.stdin ]
try: try:
while 1: while 1:
@ -31,11 +31,11 @@ except NameError:
sys.stdout.flush() sys.stdout.flush()
except: except:
import traceback import traceback
print traceback.print_exc() print(traceback.print_exc())
sys.exit(1) sys.exit(1)
print "server side starting" print("server side starting")
# server side # server side
# #
from traceback import print_exc from traceback import print_exc
@ -47,7 +47,7 @@ class promptagent(Thread):
self.clientsock = clientsock self.clientsock = clientsock
def run(self): def run(self):
print "Entering thread prompt loop" print("Entering thread prompt loop")
clientfile = self.clientsock.makefile('w') clientfile = self.clientsock.makefile('w')
filein = self.clientsock.makefile('r') filein = self.clientsock.makefile('r')
@ -58,22 +58,23 @@ class promptagent(Thread):
clientfile.write('%s %s >>> ' % loc) clientfile.write('%s %s >>> ' % loc)
clientfile.flush() clientfile.flush()
line = filein.readline() line = filein.readline()
if len(line)==0: raise EOFError,"nothing" if len(line)==0: raise EOFError("nothing")
#print >>sys.stderr,"got line: " + line #print >>sys.stderr,"got line: " + line
if line.strip(): if line.strip():
oldout, olderr = sys.stdout, sys.stderr oldout, olderr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = clientfile, clientfile sys.stdout, sys.stderr = clientfile, clientfile
try: try:
try: try:
exec compile(line + '\n','<remote pyin>', 'single') exec(compile(line + '\n','<remote pyin>', 'single'))
except: except:
print_exc() print_exc()
finally: finally:
sys.stdout=oldout sys.stdout=oldout
sys.stderr=olderr sys.stderr=olderr
clientfile.flush() clientfile.flush()
except EOFError,e: except EOFError:
print >>sys.stderr, "connection close, prompt thread returns" e = sys.exc_info()[1]
sys.stderr.write("connection close, prompt thread returns")
break break
#print >>sys.stdout, "".join(apply(format_exception,sys.exc_info())) #print >>sys.stdout, "".join(apply(format_exception,sys.exc_info()))
@ -81,4 +82,4 @@ class promptagent(Thread):
prompter = promptagent(clientsock) prompter = promptagent(clientsock)
prompter.start() prompter.start()
print "promptagent - thread started" print("promptagent - thread started")

View File

@ -22,12 +22,22 @@ if debug: # and not os.isatty(sys.stdin.fileno()):
#import py #import py
#compile = py.code.compile #compile = py.code.compile
def print_(*args):
print(" ".join(args))
if sys.version_info > (3, 0):
exec("""def exec_(source, locs):
exec(source, locs)""")
else:
exec("""def exec_(source, locs):
exec source, locs""")
def exec_from_one_connection(serversock): def exec_from_one_connection(serversock):
print progname, 'Entering Accept loop', serversock.getsockname() print_(progname, 'Entering Accept loop', serversock.getsockname())
clientsock,address = serversock.accept() clientsock,address = serversock.accept()
print progname, 'got new connection from %s %s' % address print_(progname, 'got new connection from %s %s' % address)
clientfile = clientsock.makefile('r+',0) clientfile = clientsock.makefile('r+',0)
print "reading line" print_("reading line")
# rstrip so that we can use \r\n for telnet testing # rstrip so that we can use \r\n for telnet testing
source = clientfile.readline().rstrip() source = clientfile.readline().rstrip()
clientfile.close() clientfile.close()
@ -35,11 +45,11 @@ def exec_from_one_connection(serversock):
source = eval(source) source = eval(source)
if source: if source:
co = compile(source+'\n', source, 'exec') co = compile(source+'\n', source, 'exec')
print progname, 'compiled source, executing' print_(progname, 'compiled source, executing')
try: try:
exec co in g exec_(co, g)
finally: finally:
print progname, 'finished executing code' print_(progname, 'finished executing code')
# background thread might hold a reference to this (!?) # background thread might hold a reference to this (!?)
#clientsock.close() #clientsock.close()
@ -73,11 +83,11 @@ def startserver(serversock, loop=False):
traceback.print_exc() traceback.print_exc()
else: else:
excinfo = sys.exc_info() excinfo = sys.exc_info()
print "got exception", excinfo[1] print_("got exception", excinfo[1])
if not loop: if not loop:
break break
finally: finally:
print "leaving socketserver execloop" print_("leaving socketserver execloop")
serversock.shutdown(2) serversock.shutdown(2)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -59,10 +59,10 @@ class SocketServerService(win32serviceutil.ServiceFramework):
0, # category 0, # category
servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.EVENTLOG_INFORMATION_TYPE,
(self._svc_name_, '')) (self._svc_name_, ''))
print "Begin: %s" % (self._svc_display_name_) print("Begin: %s" % (self._svc_display_name_))
hostport = ':8888' hostport = ':8888'
print 'Starting py.execnet SocketServer on %s' % hostport print('Starting py.execnet SocketServer on %s' % hostport)
serversock = socketserver.bind_and_listen(hostport) serversock = socketserver.bind_and_listen(hostport)
thread = threading.Thread(target=socketserver.startserver, thread = threading.Thread(target=socketserver.startserver,
args=(serversock,), args=(serversock,),
@ -83,7 +83,7 @@ class SocketServerService(win32serviceutil.ServiceFramework):
0, # category 0, # category
servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.EVENTLOG_INFORMATION_TYPE,
(self._svc_name_, '')) (self._svc_name_, ''))
print "End: %s" % appname print("End: %s" % appname)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -162,7 +162,8 @@ class BasicRemoteExecution:
channel = self.gw.remote_exec('def foo():\n return foobar()\nfoo()\n') channel = self.gw.remote_exec('def foo():\n return foobar()\nfoo()\n')
try: try:
channel.receive() channel.receive()
except channel.RemoteError, e: except channel.RemoteError:
e = sys.exc_info()[1]
assert str(e).startswith('Traceback (most recent call last):') assert str(e).startswith('Traceback (most recent call last):')
assert str(e).find('NameError: global name \'foobar\' ' assert str(e).find('NameError: global name \'foobar\' '
'is not defined') > -1 'is not defined') > -1
@ -174,7 +175,8 @@ class BasicRemoteExecution:
channel = self.gw.remote_exec('def foo()\n return 1\nfoo()\n') channel = self.gw.remote_exec('def foo()\n return 1\nfoo()\n')
try: try:
channel.receive() channel.receive()
except channel.RemoteError, e: except channel.RemoteError:
e = sys.exc_info()[1]
assert str(e).startswith('Traceback (most recent call last):') assert str(e).startswith('Traceback (most recent call last):')
assert str(e).find('SyntaxError') > -1 assert str(e).find('SyntaxError') > -1
@ -274,7 +276,7 @@ class BasicRemoteExecution:
if subchannel and subchannel.isclosed(): if subchannel and subchannel.isclosed():
break break
counter -= 1 counter -= 1
print counter print(counter)
if not counter: if not counter:
py.test.fail("timed out waiting for the answer[%d]" % len(l)) py.test.fail("timed out waiting for the answer[%d]" % len(l))
time.sleep(0.04) # busy-wait time.sleep(0.04) # busy-wait

View File

@ -8,8 +8,8 @@ def test_apiwarn_functional():
capture = py.io.StdCapture() capture = py.io.StdCapture()
py.log._apiwarn("x.y.z", "something") py.log._apiwarn("x.y.z", "something")
out, err = capture.reset() out, err = capture.reset()
print "out", out py.builtin.print_("out", out)
print "err", err py.builtin.print_("err", err)
assert err.find("x.y.z") != -1 assert err.find("x.y.z") != -1
lno = test_apiwarn_functional.func_code.co_firstlineno + 2 lno = test_apiwarn_functional.func_code.co_firstlineno + 2
exp = "%s:%s" % (mypath, lno) exp = "%s:%s" % (mypath, lno)
@ -57,8 +57,8 @@ def test_function():
capture = py.io.StdCapture() capture = py.io.StdCapture()
py.log._apiwarn("x.y.z", "something", function=test_function) py.log._apiwarn("x.y.z", "something", function=test_function)
out, err = capture.reset() out, err = capture.reset()
print "out", out py.builtin.print_("out", out)
print "err", err py.builtin.print_("err", err)
assert err.find("x.y.z") != -1 assert err.find("x.y.z") != -1
lno = test_function.func_code.co_firstlineno lno = test_function.func_code.co_firstlineno
exp = "%s:%s" % (mypath, lno) exp = "%s:%s" % (mypath, lno)

View File

@ -62,4 +62,4 @@ if __name__ == '__main__':
""") """)
c.send(channel) c.send(channel)
c.send(srv.p2c(py.path.local('/tmp'))) c.send(srv.p2c(py.path.local('/tmp')))
print c.receive() print(c.receive())

View File

@ -42,7 +42,7 @@ class TestLocalPath(LocalSetup, CommonFSTests):
def test_remove_removes_readonly_dir(self): def test_remove_removes_readonly_dir(self):
readonly_dir = self.tmpdir.join('readonlydir').ensure(dir=1) readonly_dir = self.tmpdir.join('readonlydir').ensure(dir=1)
readonly_dir.chmod(0500) readonly_dir.chmod(int("500", 8))
readonly_dir.remove() readonly_dir.remove()
assert not readonly_dir.check(exists=1) assert not readonly_dir.check(exists=1)
@ -223,7 +223,7 @@ class TestExecution(LocalSetup):
finally: finally:
env['PATH'] = oldpath env['PATH'] = oldpath
noperm.chmod(0644) noperm.chmod(int("644", 8))
noperm.remove() noperm.remove()
def test_sysfind_absolute(self): def test_sysfind_absolute(self):
@ -367,13 +367,13 @@ class TestWINLocalPath:
py.test.raises(NotImplementedError, "self.root.stat().group") py.test.raises(NotImplementedError, "self.root.stat().group")
def test_chmod_simple_int(self): def test_chmod_simple_int(self):
print "self.root is", self.root py.builtin.print_("self.root is", self.root)
mode = self.root.stat().mode mode = self.root.stat().mode
# Ensure that we actually change the mode to something different. # Ensure that we actually change the mode to something different.
self.root.chmod(mode == 0 and 1 or 0) self.root.chmod(mode == 0 and 1 or 0)
try: try:
print self.root.stat().mode print(self.root.stat().mode)
print mode print(mode)
assert self.root.stat().mode != mode assert self.root.stat().mode != mode
finally: finally:
self.root.chmod(mode) self.root.chmod(mode)
@ -553,7 +553,7 @@ class TestPOSIXLocalPath:
assert self.root == nroot assert self.root == nroot
def test_chmod_simple_int(self): def test_chmod_simple_int(self):
print "self.root is", self.root py.builtin.print_("self.root is", self.root)
mode = self.root.stat().mode mode = self.root.stat().mode
self.root.chmod(mode/2) self.root.chmod(mode/2)
try: try:
@ -564,15 +564,15 @@ class TestPOSIXLocalPath:
def test_chmod_rec_int(self): def test_chmod_rec_int(self):
# XXX fragile test # XXX fragile test
print "self.root is", self.root py.builtin.print_("self.root is", self.root)
recfilter = lambda x: x.check(dotfile=0, link=0) recfilter = lambda x: x.check(dotfile=0, link=0)
oldmodes = {} oldmodes = {}
for x in self.root.visit(rec=recfilter): for x in self.root.visit(rec=recfilter):
oldmodes[x] = x.stat().mode oldmodes[x] = x.stat().mode
self.root.chmod(0772, rec=recfilter) self.root.chmod(int("772", 8), rec=recfilter)
try: try:
for x in self.root.visit(rec=recfilter): for x in self.root.visit(rec=recfilter):
assert x.stat().mode & 0777 == 0772 assert x.stat().mode & int("777", 8) == int("772", 8)
finally: finally:
for x,y in oldmodes.items(): for x,y in oldmodes.items():
x.chmod(y) x.chmod(y)

View File

@ -36,8 +36,8 @@ def serve_bg(repopath):
port, pidfile, repopath) port, pidfile, repopath)
try: try:
py.process.cmdexec(cmd) py.process.cmdexec(cmd)
except py.process.cmdexec.Error, e: except py.process.cmdexec.Error:
pass e = sys.exc_info()[1]
else: else:
# XXX we assume here that the pid file gets written somewhere, I # XXX we assume here that the pid file gets written somewhere, I
# guess this should be relatively safe... (I hope, at least?) # guess this should be relatively safe... (I hope, at least?)
@ -276,8 +276,8 @@ class SvnAuthFunctionalTestBase(object):
make_repo_auth(self.repopath, {'johnny': ('foo', 'rw')}) make_repo_auth(self.repopath, {'johnny': ('foo', 'rw')})
try: try:
return serve_bg(self.repopath.dirpath()) return serve_bg(self.repopath.dirpath())
except IOError, e: except IOError:
py.test.skip(str(e)) py.test.skip(str(sys.exc_info()[1]))
class TestSvnWCAuthFunctional(SvnAuthFunctionalTestBase): class TestSvnWCAuthFunctional(SvnAuthFunctionalTestBase):
def test_checkout_constructor_arg(self): def test_checkout_constructor_arg(self):

View File

@ -50,7 +50,7 @@ def convert_dot(fn, new_extension):
if not py.path.local.sysfind("dot"): if not py.path.local.sysfind("dot"):
raise SystemExit("ERROR: dot not found") raise SystemExit("ERROR: dot not found")
result = fn.new(ext=new_extension) result = fn.new(ext=new_extension)
print result print(result)
arg = "-T%s" % (format_to_dotargument[new_extension], ) arg = "-T%s" % (format_to_dotargument[new_extension], )
py.std.os.system('dot "%s" "%s" > "%s"' % (arg, fn, result)) py.std.os.system('dot "%s" "%s" > "%s"' % (arg, fn, result))
if new_extension == "eps": if new_extension == "eps":

View File

@ -26,7 +26,7 @@ else:
class ImageClass(object): class ImageClass(object):
option_spec = images.image.options option_spec = images.image.options
def run(self): def run(self):
return images.image(u'image', return images.image('image',
self.arguments, self.arguments,
self.options, self.options,
self.content, self.content,
@ -51,7 +51,7 @@ class GraphvizDirective(ImageClass):
self.state.document.settings._source) self.state.document.settings._source)
text = self.block_text.replace("graphviz", "image", 1) text = self.block_text.replace("graphviz", "image", 1)
self.block_text = text.replace(self.arguments[0], newname, 1) self.block_text = text.replace(self.arguments[0], newname, 1)
self.name = u'image' self.name = 'image'
self.arguments = [newname] self.arguments = [newname]
return ImageClass.run(self) return ImageClass.run(self)

View File

@ -132,15 +132,16 @@ def process_rest_file(restfile, stylesheet=None, debug=False, rest_options=None)
while i < 10: # there should never be as many as five reruns, but to be sure while i < 10: # there should never be as many as five reruns, but to be sure
try: try:
latexoutput = py.process.cmdexec('pdflatex "%s"' % (tex, )) latexoutput = py.process.cmdexec('pdflatex "%s"' % (tex, ))
except ExecutionFailed, e: except ExecutionFailed:
print "ERROR: pdflatex execution failed" e = py.std.sys.exc_info()[1]
print "pdflatex stdout:" print("ERROR: pdflatex execution failed")
print e.out print("pdflatex stdout:")
print "pdflatex stderr:" print(e.out)
print e.err print("pdflatex stderr:")
print(e.err)
raise SystemExit raise SystemExit
if debug: if debug:
print latexoutput print(latexoutput)
if py.std.re.search("LaTeX Warning:.*Rerun", latexoutput) is None: if py.std.re.search("LaTeX Warning:.*Rerun", latexoutput) is None:
break break
i += 1 i += 1

View File

@ -4,7 +4,7 @@ import re
if hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()): if hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()):
def log(msg): def log(msg):
print msg print(msg)
else: else:
def log(msg): def log(msg):
pass pass
@ -59,8 +59,14 @@ def process(txtpath, encoding='latin1'):
# info = txtpath.info() # info = txtpath.info()
# svninfopath.dump(info) # svninfopath.dump(info)
rex1 = re.compile(ur'.*<body>(.*)</body>.*', re.MULTILINE | re.DOTALL) if sys.version_info > (3, 0):
rex2 = re.compile(ur'.*<div class="document">(.*)</div>.*', re.MULTILINE | re.DOTALL) def _uni(s): return s
else:
def _uni(s):
return unicode(s)
rex1 = re.compile(r'.*<body>(.*)</body>.*', re.MULTILINE | re.DOTALL)
rex2 = re.compile(r'.*<div class="document">(.*)</div>.*', re.MULTILINE | re.DOTALL)
def strip_html_header(string, encoding='utf8'): def strip_html_header(string, encoding='utf8'):
""" return the content of the body-tag """ """ return the content of the body-tag """

View File

@ -128,8 +128,8 @@ class Rest(AbstractNode):
outcome = [] outcome = []
if (isinstance(self.children[0], Transition) or if (isinstance(self.children[0], Transition) or
isinstance(self.children[-1], Transition)): isinstance(self.children[-1], Transition)):
raise ValueError, ('document must not begin or end with a ' raise ValueError('document must not begin or end with a '
'transition') 'transition')
for child in self.children: for child in self.children:
outcome.append(child.text()) outcome.append(child.text())

View File

@ -149,8 +149,8 @@ turpis. Etiam et ipsum. Quisque at lacus. Etiam pellentesque, enim porta
pulvinar viverra, libero elit iaculis justo, vitae convallis pede purus vel pulvinar viverra, libero elit iaculis justo, vitae convallis pede purus vel
arcu. Morbi aliquam lacus et urna. Donec commodo pellentesque mi.""" arcu. Morbi aliquam lacus et urna. Donec commodo pellentesque mi."""
txt = Paragraph(text, width=80).text() txt = Paragraph(text, width=80).text()
print repr(txt) print(repr(txt))
print repr(expected) print(repr(expected))
assert txt == expected assert txt == expected
checkrest(txt) checkrest(txt)
@ -172,7 +172,7 @@ Paragraph
""" """
txt = Rest(Paragraph("Text"), LiteralBlock("def fun():\n some"), \ txt = Rest(Paragraph("Text"), LiteralBlock("def fun():\n some"), \
Paragraph("Paragraph")).text() Paragraph("Paragraph")).text()
print repr(txt) print(repr(txt))
assert txt == expected assert txt == expected
checkrest(txt) checkrest(txt)
@ -183,7 +183,7 @@ Foo
Bar Bar
""" """
txt = Rest(Paragraph('Foo'), LiteralBlock(''), Paragraph('Bar')).text() txt = Rest(Paragraph('Foo'), LiteralBlock(''), Paragraph('Bar')).text()
print repr(txt) print(repr(txt))
assert txt == expected assert txt == expected
checkrest(txt) checkrest(txt)
@ -359,7 +359,7 @@ def test_nested_nested_lists():
""" """
txt = Rest(ListItem('foo', ListItem('bar', ListItem('baz')), txt = Rest(ListItem('foo', ListItem('bar', ListItem('baz')),
ListItem('qux')), ListItem('quux')).text() ListItem('qux')), ListItem('quux')).text()
print txt print(txt)
assert txt == expected assert txt == expected
checkrest(txt) checkrest(txt)

View File

@ -53,6 +53,6 @@ class TestCase(object):
""" % locals() ) """ % locals() )
source = "".join(items) source = "".join(items)
exec py.code.Source(source).compile() exec(py.code.Source(source).compile())
__all__ = ['TestCase'] __all__ = ['TestCase']

View File

@ -23,7 +23,7 @@ class MockNode:
def dumpqueue(queue): def dumpqueue(queue):
while queue.qsize(): while queue.qsize():
print queue.get() print(queue.get())
class TestDSession: class TestDSession:
def test_add_remove_node(self, testdir): def test_add_remove_node(self, testdir):
@ -184,7 +184,7 @@ class TestDSession:
when = "call" when = "call"
session.queueevent("pytest_runtest_logreport", report=rep) session.queueevent("pytest_runtest_logreport", report=rep)
reprec = testdir.getreportrecorder(session) reprec = testdir.getreportrecorder(session)
print session.item2nodes print(session.item2nodes)
loopstate = session._initloopstate([]) loopstate = session._initloopstate([])
assert len(session.item2nodes[item1]) == 2 assert len(session.item2nodes[item1]) == 2
session.loop_once(loopstate) session.loop_once(loopstate)
@ -215,7 +215,7 @@ class TestDSession:
item1.config.option.dist = "load" item1.config.option.dist = "load"
session.queueevent("pytest_testnodedown", node=node, error="xyz") session.queueevent("pytest_testnodedown", node=node, error="xyz")
reprec = testdir.getreportrecorder(session) reprec = testdir.getreportrecorder(session)
print session.item2nodes print(session.item2nodes)
loopstate = session._initloopstate([]) loopstate = session._initloopstate([])
session.loop_once(loopstate) session.loop_once(loopstate)

View File

@ -20,7 +20,7 @@ class TestNodeManager:
nodemanager.rsync_roots() nodemanager.rsync_roots()
p, = nodemanager.gwmanager.multi_exec("import os ; channel.send(os.getcwd())").receive_each() p, = nodemanager.gwmanager.multi_exec("import os ; channel.send(os.getcwd())").receive_each()
p = py.path.local(p) p = py.path.local(p)
print "remote curdir", p py.builtin.print_("remote curdir", p)
assert p == mysetup.dest.join(config.topdir.basename) assert p == mysetup.dest.join(config.topdir.basename)
assert p.join("dir1").check() assert p.join("dir1").check()
assert p.join("dir1", "file1").check() assert p.join("dir1", "file1").check()

View File

@ -17,7 +17,7 @@ class EventQueue:
except py.std.Queue.Empty: except py.std.Queue.Empty:
#print "node channel", self.node.channel #print "node channel", self.node.channel
#print "remoteerror", self.node.channel._getremoteerror() #print "remoteerror", self.node.channel._getremoteerror()
print "seen events", events py.builtin.print_("seen events", events)
raise IOError("did not see %r events" % (eventname)) raise IOError("did not see %r events" % (eventname))
else: else:
name, args, kwargs = eventcall name, args, kwargs = eventcall
@ -28,7 +28,7 @@ class EventQueue:
return kwargs return kwargs
events.append(name) events.append(name)
if name == "pytest_internalerror": if name == "pytest_internalerror":
print str(kwargs["excrepr"]) py.builtin.print_(str(kwargs["excrepr"]))
class MySetup: class MySetup:
def __init__(self, request): def __init__(self, request):
@ -55,7 +55,7 @@ class MySetup:
def xfinalize(self): def xfinalize(self):
if hasattr(self, 'node'): if hasattr(self, 'node'):
gw = self.node.gateway gw = self.node.gateway
print "exiting:", gw py.builtin.print_("exiting:", gw)
gw.exit() gw.exit()
def pytest_funcarg__mysetup(request): def pytest_funcarg__mysetup(request):
@ -117,7 +117,7 @@ class TestMasterSlaveConnection:
kwargs = mysetup.geteventargs("pytest_runtest_logreport") kwargs = mysetup.geteventargs("pytest_runtest_logreport")
rep = kwargs['report'] rep = kwargs['report']
assert rep.passed assert rep.passed
print rep py.builtin.print_(rep)
assert rep.item == item assert rep.item == item
def test_send_some(self, testdir, mysetup): def test_send_some(self, testdir, mysetup):

View File

@ -66,7 +66,7 @@ class TXNode(object):
raise raise
except: except:
excinfo = py.code.ExceptionInfo() excinfo = py.code.ExceptionInfo()
print "!" * 20, excinfo py.builtin.print_("!" * 20, excinfo)
self.config.pluginmanager.notify_exception(excinfo) self.config.pluginmanager.notify_exception(excinfo)
def send(self, item): def send(self, item):

View File

@ -51,7 +51,7 @@ class RemoteControl(object):
def trace(self, *args): def trace(self, *args):
if self.config.option.debug: if self.config.option.debug:
msg = " ".join([str(x) for x in args]) msg = " ".join([str(x) for x in args])
print "RemoteControl:", msg py.builtin.print_("RemoteControl:", msg)
def initgateway(self): def initgateway(self):
return py.execnet.PopenGateway() return py.execnet.PopenGateway()
@ -97,7 +97,8 @@ class RemoteControl(object):
self.channel.send(trails) self.channel.send(trails)
try: try:
return self.channel.receive() return self.channel.receive()
except self.channel.RemoteError, e: except self.channel.RemoteError:
e = sys.exc_info()[1]
self.trace("ERROR", e) self.trace("ERROR", e)
raise raise
finally: finally:
@ -107,7 +108,7 @@ def slave_runsession(channel, config, fullwidth, hasmarkup):
""" we run this on the other side. """ """ we run this on the other side. """
if config.option.debug: if config.option.debug:
def DEBUG(*args): def DEBUG(*args):
print " ".join(map(str, args)) print(" ".join(map(str, args)))
else: else:
def DEBUG(*args): pass def DEBUG(*args): pass
@ -128,7 +129,7 @@ def slave_runsession(channel, config, fullwidth, hasmarkup):
for trail in trails: for trail in trails:
try: try:
colitem = py.test.collect.Collector._fromtrail(trail, config) colitem = py.test.collect.Collector._fromtrail(trail, config)
except AssertionError, e: except AssertionError:
#XXX send info for "test disappeared" or so #XXX send info for "test disappeared" or so
continue continue
colitems.append(colitem) colitems.append(colitem)

View File

@ -38,7 +38,7 @@ class StatRecorder:
if oldstat.mtime != curstat.mtime or \ if oldstat.mtime != curstat.mtime or \
oldstat.size != curstat.size: oldstat.size != curstat.size:
changed = True changed = True
print "# MODIFIED", path py.builtin.print_("# MODIFIED", path)
if removepycfiles and path.ext == ".py": if removepycfiles and path.ext == ".py":
pycfile = path + "c" pycfile = path + "c"
if pycfile.check(): if pycfile.check():

View File

@ -29,8 +29,8 @@ class PylintItem(py.test.collect.Item):
finally: finally:
out, err = capture.reset() out, err = capture.reset()
rating = out.strip().split('\n')[-1] rating = out.strip().split('\n')[-1]
print ">>>", sys.stdout.write(">>>")
print rating print(rating)
assert 0 assert 0

View File

@ -135,7 +135,7 @@ class ReSTSyntaxTest(py.test.collect.Item):
lexer = TextLexer() lexer = TextLexer()
# take an arbitrary option if more than one is given # take an arbitrary option if more than one is given
formatter = options and VARIANTS[options.keys()[0]] or DEFAULT formatter = options and VARIANTS[options.keys()[0]] or DEFAULT
parsed = highlight(u'\n'.join(content), lexer, formatter) parsed = highlight('\n'.join(content), lexer, formatter)
return [nodes.raw('', parsed, format='html')] return [nodes.raw('', parsed, format='html')]
pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS]) pygments_directive.options = dict([(key, directives.flag) for key in VARIANTS])
@ -215,14 +215,15 @@ class DoctestText(py.test.collect.Item):
for line in deindent(s).split('\n'): for line in deindent(s).split('\n'):
stripped = line.strip() stripped = line.strip()
if skipchunk and line.startswith(skipchunk): if skipchunk and line.startswith(skipchunk):
print "skipping", line py.builtin.print_("skipping", line)
continue continue
skipchunk = False skipchunk = False
if stripped.startswith(prefix): if stripped.startswith(prefix):
try: try:
exec py.code.Source(stripped[len(prefix):]).compile() in \ py.builtin.exec_(py.code.Source(
mod.__dict__ stripped[len(prefix):]).compile(), mod.__dict__)
except ValueError, e: except ValueError:
e = sys.exc_info()[1]
if e.args and e.args[0] == "skipchunk": if e.args and e.args[0] == "skipchunk":
skipchunk = " " * (len(line) - len(line.lstrip())) skipchunk = " " * (len(line) - len(line.lstrip()))
else: else:
@ -301,11 +302,12 @@ def urlcheck(tryfn, path, lineno, TIMEOUT_URLOPEN):
py.std.socket.setdefaulttimeout(TIMEOUT_URLOPEN) py.std.socket.setdefaulttimeout(TIMEOUT_URLOPEN)
try: try:
try: try:
print "trying remote", tryfn py.builtin.print_("trying remote", tryfn)
py.std.urllib2.urlopen(tryfn) py.std.urllib2.urlopen(tryfn)
finally: finally:
py.std.socket.setdefaulttimeout(old) py.std.socket.setdefaulttimeout(old)
except (py.std.urllib2.URLError, py.std.urllib2.HTTPError), e: except (py.std.urllib2.URLError, py.std.urllib2.HTTPError):
e = sys.exc_info()[1]
if getattr(e, 'code', None) in (401, 403): # authorization required, forbidden if getattr(e, 'code', None) in (401, 403): # authorization required, forbidden
py.test.skip("%s: %s" %(tryfn, str(e))) py.test.skip("%s: %s" %(tryfn, str(e)))
else: else:
@ -325,7 +327,7 @@ def localrefcheck(tryfn, path, lineno):
fn = path.dirpath(tryfn) fn = path.dirpath(tryfn)
ishtml = fn.ext == '.html' ishtml = fn.ext == '.html'
fn = ishtml and fn.new(ext='.txt') or fn fn = ishtml and fn.new(ext='.txt') or fn
print "filename is", fn py.builtin.print_("filename is", fn)
if not fn.check(): # not ishtml or not fn.check(): if not fn.check(): # not ishtml or not fn.check():
if not py.path.local(tryfn).check(): # the html could be there if not py.path.local(tryfn).check(): # the html could be there
py.test.fail("reference error %r in %s:%d" %( py.test.fail("reference error %r in %s:%d" %(
@ -338,7 +340,7 @@ def localrefcheck(tryfn, path, lineno):
match2 = ".. _`%s`:" % anchor match2 = ".. _`%s`:" % anchor
match3 = ".. _%s:" % anchor match3 = ".. _%s:" % anchor
candidates = (anchor, match2, match3) candidates = (anchor, match2, match3)
print "candidates", repr(candidates) py.builtin.print_("candidates", repr(candidates))
for line in source.split('\n'): for line in source.split('\n'):
line = line.strip() line = line.strip()
if line in candidates: if line in candidates:

View File

@ -78,7 +78,7 @@ class BaseFunctionalTests:
def test_func(): def test_func():
pass pass
""") """)
print reports print(reports)
rep = reports[0] rep = reports[0]
assert not rep.failed assert not rep.failed
assert not rep.passed assert not rep.passed
@ -112,7 +112,7 @@ class BaseFunctionalTests:
def test_func(): def test_func():
pass pass
""") """)
print reports print(reports)
assert len(reports) == 3 assert len(reports) == 3
rep = reports[2] rep = reports[2]
assert not rep.skipped assert not rep.skipped
@ -159,7 +159,7 @@ class BaseFunctionalTests:
""") """)
assert len(reports) == 2 assert len(reports) == 2
rep = reports[0] rep = reports[0]
print rep print(rep)
assert not rep.skipped assert not rep.skipped
assert not rep.passed assert not rep.passed
assert rep.failed assert rep.failed
@ -206,7 +206,7 @@ class TestExecutionNonForked(BaseFunctionalTests):
def test_func(): def test_func():
raise KeyboardInterrupt("fake") raise KeyboardInterrupt("fake")
""") """)
except KeyboardInterrupt, e: except KeyboardInterrupt:
pass pass
else: else:
py.test.fail("did not raise") py.test.fail("did not raise")

View File

@ -175,7 +175,7 @@ class TestTerminal:
g() # --calling-- g() # --calling--
""") """)
for tbopt in ["long", "short", "no"]: for tbopt in ["long", "short", "no"]:
print 'testing --tb=%s...' % tbopt print('testing --tb=%s...' % tbopt)
result = testdir.runpytest('--tb=%s' % tbopt) result = testdir.runpytest('--tb=%s' % tbopt)
s = result.stdout.str() s = result.stdout.str()
if tbopt == "long": if tbopt == "long":

View File

@ -1,5 +1,6 @@
import sys import sys
import os import os
import py
def setup_module(mod=None): def setup_module(mod=None):
if mod is None: if mod is None:
@ -37,12 +38,12 @@ def test_import():
if mod1 is not mod2: if mod1 is not mod2:
bad_matches.append((name1, mod1, name2, mod2)) bad_matches.append((name1, mod1, name2, mod2))
for name1, mod1, name2, mod2 in bad_matches: for name1, mod1, name2, mod2 in bad_matches:
print "These modules should be identical:" print("These modules should be identical:")
print " %s:" % name1 print(" %s:" % name1)
print " ", mod1 print(" ", mod1)
print " %s:" % name2 print(" %s:" % name2)
print " ", mod2 print(" ", mod2)
print py.builtin.print_()
if bad_matches: if bad_matches:
assert False assert False

View File

@ -81,9 +81,9 @@ class TestCollector:
def test_listnames_and__getitembynames(self, testdir): def test_listnames_and__getitembynames(self, testdir):
modcol = testdir.getmodulecol("pass", withinit=True) modcol = testdir.getmodulecol("pass", withinit=True)
print modcol.config.pluginmanager.getplugins() print(modcol.config.pluginmanager.getplugins())
names = modcol.listnames() names = modcol.listnames()
print names print(names)
dircol = modcol.config.getfsnode(modcol.config.topdir) dircol = modcol.config.getfsnode(modcol.config.topdir)
x = dircol._getitembynames(names) x = dircol._getitembynames(names)
assert modcol.name == x.name assert modcol.name == x.name

View File

@ -50,4 +50,4 @@ class TestCompatAssertions(TestCase):
self.%(name)s, %(paramfail)s) self.%(name)s, %(paramfail)s)
""" % locals() """ % locals()
co = py.code.Source(source).compile() co = py.code.Source(source).compile()
exec co exec(co)

View File

@ -132,7 +132,7 @@ class TestConfigAPI:
config = py.test.config._reparse([p]) config = py.test.config._reparse([p])
assert config.getconftest_pathlist('notexist') is None assert config.getconftest_pathlist('notexist') is None
pl = config.getconftest_pathlist('pathlist') pl = config.getconftest_pathlist('pathlist')
print pl print(pl)
assert len(pl) == 2 assert len(pl) == 2
assert pl[0] == tmpdir assert pl[0] == tmpdir
assert pl[1] == somepath assert pl[1] == somepath
@ -195,7 +195,7 @@ class TestConfigApi_getcolitems:
config = py.test.config._reparse([x]) config = py.test.config._reparse([x])
col = config.getfsnode(x) col = config.getfsnode(x)
assert isinstance(col, py.test.collect.Directory) assert isinstance(col, py.test.collect.Directory)
print col.listchain() print(col.listchain())
assert col.name == 'a' assert col.name == 'a'
assert col.parent is None assert col.parent is None
assert col.config is config assert col.config is config

View File

@ -179,7 +179,7 @@ class TestRequest:
ss = item.config._setupstate ss = item.config._setupstate
assert not teardownlist assert not teardownlist
ss.teardown_exact(item) ss.teardown_exact(item)
print ss.stack print(ss.stack)
assert teardownlist == [1] assert teardownlist == [1]
def test_request_addfinalizer_partial_setup_failure(self, testdir): def test_request_addfinalizer_partial_setup_failure(self, testdir):

View File

@ -58,7 +58,7 @@ class Test_genitems:
s = items[0].getmodpath(stopatmodule=False) s = items[0].getmodpath(stopatmodule=False)
assert s.endswith("test_example_items1.testone") assert s.endswith("test_example_items1.testone")
print s print(s)
class TestKeywordSelection: class TestKeywordSelection:
@ -98,7 +98,7 @@ class TestKeywordSelection:
for keyword in ('xxx', 'xxx test_2', 'TestClass', 'xxx -test_1', for keyword in ('xxx', 'xxx test_2', 'TestClass', 'xxx -test_1',
'TestClass test_2', 'xxx TestClass test_2',): 'TestClass test_2', 'xxx TestClass test_2',):
reprec = testdir.inline_run(p.dirpath(), '-s', '-k', keyword) reprec = testdir.inline_run(p.dirpath(), '-s', '-k', keyword)
print "keyword", repr(keyword) py.builtin.print_("keyword", repr(keyword))
passed, skipped, failed = reprec.listoutcomes() passed, skipped, failed = reprec.listoutcomes()
assert len(passed) == 1 assert len(passed) == 1
assert passed[0].item.name == "test_2" assert passed[0].item.name == "test_2"

View File

@ -32,7 +32,7 @@ def test_importorskip():
py.test.importorskip("hello123", minversion="5.0") py.test.importorskip("hello123", minversion="5.0")
""") """)
except Skipped: except Skipped:
print py.code.ExceptionInfo() print(py.code.ExceptionInfo())
py.test.fail("spurious skip") py.test.fail("spurious skip")
def test_pytest_exit(): def test_pytest_exit():

View File

@ -3,11 +3,11 @@ import py
def setglobals(request): def setglobals(request):
oldconfig = py.test.config oldconfig = py.test.config
oldcom = py._com.comregistry oldcom = py._com.comregistry
print "setting py.test.config to None" print("setting py.test.config to None")
py.test.config = None py.test.config = None
py._com.comregistry = py._com.Registry() py._com.comregistry = py._com.Registry()
def resetglobals(): def resetglobals():
print "setting py.test.config to", oldconfig py.builtin.print_("setting py.test.config to", oldconfig)
py.test.config = oldconfig py.test.config = oldconfig
py._com.comregistry = oldcom py._com.comregistry = oldcom
request.addfinalizer(resetglobals) request.addfinalizer(resetglobals)

View File

@ -169,7 +169,7 @@ class TestPytestPluginInteractions:
""") """)
config = Config() config = Config()
config._conftest.importconftest(p) config._conftest.importconftest(p)
print config.pluginmanager.getplugins() print(config.pluginmanager.getplugins())
config.parse([]) config.parse([])
assert not config.option.test123 assert not config.option.test123

View File

@ -57,7 +57,7 @@ class SessionTests:
assert len(failed) == 1 assert len(failed) == 1
out = failed[0].longrepr.reprcrash.message out = failed[0].longrepr.reprcrash.message
if not out.find("DID NOT RAISE") != -1: if not out.find("DID NOT RAISE") != -1:
print out print(out)
py.test.fail("incorrect raises() output") py.test.fail("incorrect raises() output")
def test_generator_yields_None(self, testdir): def test_generator_yields_None(self, testdir):

View File

@ -2,6 +2,7 @@ import Queue
import threading import threading
import time import time
import sys import sys
import py
ERRORMARKER = object() ERRORMARKER = object()
@ -52,7 +53,7 @@ class Reply(object):
if result is ERRORMARKER: if result is ERRORMARKER:
self._queue = None self._queue = None
excinfo = self._excinfo excinfo = self._excinfo
raise excinfo[0], excinfo[1], excinfo[2] py.builtin._reraise(excinfo[0], excinfo[1], excinfo[2])
return result return result
class WorkerThread(threading.Thread): class WorkerThread(threading.Thread):

View File

@ -17,7 +17,7 @@ class TestThreadOut:
try: try:
l = [] l = []
out.setwritefunc(l.append) out.setwritefunc(l.append)
print 42,13, py.builtin.print_(42,13)
x = l.pop(0) x = l.pop(0)
assert x == '42' assert x == '42'
x = l.pop(0) x = l.pop(0)
@ -34,9 +34,9 @@ class TestThreadOut:
defaults = [] defaults = []
def f(l): def f(l):
out.setwritefunc(l.append) out.setwritefunc(l.append)
print id(l), print(id(l))
out.delwritefunc() out.delwritefunc()
print 1 print(1)
out.setdefaultwriter(defaults.append) out.setdefaultwriter(defaults.append)
pool = WorkerPool() pool = WorkerPool()
listlist = [] listlist = []
@ -46,7 +46,7 @@ class TestThreadOut:
pool.dispatch(f, l) pool.dispatch(f, l)
pool.shutdown() pool.shutdown()
for name, value in out.__dict__.items(): for name, value in out.__dict__.items():
print >>sys.stderr, "%s: %s" %(name, value) sys.stderr.write("%s: %s\n" %(name, value))
pool.join(2.0) pool.join(2.0)
for i in range(num): for i in range(num):
item = listlist[i] item = listlist[i]

View File

@ -88,6 +88,6 @@ def test_pool_clean_shutdown():
assert not pool._alive assert not pool._alive
assert not pool._ready assert not pool._ready
out, err = capture.reset() out, err = capture.reset()
print out print(out)
print >>sys.stderr, err sys.stderr.write(err + "\n")
assert err == '' assert err == ''

View File

@ -28,11 +28,16 @@ class HtmlVisitor(SimpleUnicodeVisitor):
def _isinline(self, tagname): def _isinline(self, tagname):
return tagname in self.inline return tagname in self.inline
if sys.version_info > (3, 0):
def u(s): return s
else:
def u(s): return unicode(s)
class HtmlTag(Tag): class HtmlTag(Tag):
def unicode(self, indent=2): def unicode(self, indent=2):
l = [] l = []
HtmlVisitor(l.append, indent, shortempty=False).visit(self) HtmlVisitor(l.append, indent, shortempty=False).visit(self)
return u"".join(l) return u("").join(l)
# exported plain html namespace # exported plain html namespace
class html(Namespace): class html(Namespace):

View File

@ -1,11 +1,20 @@
import re import re
import sys
if sys.version_info > (3, 0):
def u(s):
return s
else:
def u(s):
return unicode(s)
class _escape: class _escape:
def __init__(self): def __init__(self):
self.escape = { self.escape = {
u'"' : u'&quot;', u'<' : u'&lt;', u'>' : u'&gt;', u('"') : u('&quot;'), u('<') : u('&lt;'), u('>') : u('&gt;'),
u'&' : u'&amp;', u"'" : u'&apos;', u('&') : u('&amp;'), u("'") : u('&apos;'),
} }
self.charef_rex = re.compile(u"|".join(self.escape.keys())) self.charef_rex = re.compile(u("|").join(self.escape.keys()))
def _replacer(self, match): def _replacer(self, match):
return self.escape[match.group(0)] return self.escape[match.group(0)]

View File

@ -2,8 +2,16 @@
# a generic conversion serializer # a generic conversion serializer
# #
import sys
from py.xml import escape from py.xml import escape
if sys.version_info > (3, 0):
def u(s):
return s
else:
def u(s):
return unicode(s)
class SimpleUnicodeVisitor(object): class SimpleUnicodeVisitor(object):
""" recursive visitor to write unicode. """ """ recursive visitor to write unicode. """
def __init__(self, write, indent=0, curindent=0, shortempty=True): def __init__(self, write, indent=0, curindent=0, shortempty=True):
@ -51,21 +59,21 @@ class SimpleUnicodeVisitor(object):
self.visited[id(tag)] = 1 self.visited[id(tag)] = 1
tagname = getattr(tag, 'xmlname', tag.__class__.__name__) tagname = getattr(tag, 'xmlname', tag.__class__.__name__)
if self.curindent and not self._isinline(tagname): if self.curindent and not self._isinline(tagname):
self.write("\n" + u' ' * self.curindent) self.write("\n" + u(' ') * self.curindent)
if tag: if tag:
self.curindent += self.indent self.curindent += self.indent
self.write(u'<%s%s>' % (tagname, self.attributes(tag))) self.write(u('<%s%s>') % (tagname, self.attributes(tag)))
self.parents.append(tag) self.parents.append(tag)
map(self.visit, tag) map(self.visit, tag)
self.parents.pop() self.parents.pop()
self.write(u'</%s>' % tagname) self.write(u('</%s>') % tagname)
self.curindent -= self.indent self.curindent -= self.indent
else: else:
nameattr = tagname+self.attributes(tag) nameattr = tagname+self.attributes(tag)
if self._issingleton(tagname): if self._issingleton(tagname):
self.write(u'<%s/>' % (nameattr,)) self.write(u('<%s/>') % (nameattr,))
else: else:
self.write(u'<%s></%s>' % (nameattr, tagname)) self.write(u('<%s></%s>') % (nameattr, tagname))
def attributes(self, tag): def attributes(self, tag):
# serialize attributes # serialize attributes
@ -77,14 +85,14 @@ class SimpleUnicodeVisitor(object):
if res is not None: if res is not None:
l.append(res) l.append(res)
l.extend(self.getstyle(tag)) l.extend(self.getstyle(tag))
return u"".join(l) return u("").join(l)
def repr_attribute(self, attrs, name): def repr_attribute(self, attrs, name):
if name[:2] != '__': if name[:2] != '__':
value = getattr(attrs, name) value = getattr(attrs, name)
if name.endswith('_'): if name.endswith('_'):
name = name[:-1] name = name[:-1]
return u' %s="%s"' % (name, escape(unicode(value))) return u(' %s="%s"') % (name, escape(unicode(value)))
def getstyle(self, tag): def getstyle(self, tag):
""" return attribute list suitable for styling. """ """ return attribute list suitable for styling. """
@ -94,7 +102,7 @@ class SimpleUnicodeVisitor(object):
return [] return []
else: else:
stylelist = [x+': ' + y for x,y in styledict.items()] stylelist = [x+': ' + y for x,y in styledict.items()]
return [u' style="%s"' % u'; '.join(stylelist)] return [u(' style="%s"') % u('; ').join(stylelist)]
def _issingleton(self, tagname): def _issingleton(self, tagname):
"""can (and will) be overridden in subclasses""" """can (and will) be overridden in subclasses"""

View File

@ -18,7 +18,7 @@ class Tag(list):
from py.__.xmlobj.visit import SimpleUnicodeVisitor from py.__.xmlobj.visit import SimpleUnicodeVisitor
l = [] l = []
SimpleUnicodeVisitor(l.append, indent).visit(self) SimpleUnicodeVisitor(l.append, indent).visit(self)
return u"".join(l) return "".join(l)
def __repr__(self): def __repr__(self):
name = self.__class__.__name__ name = self.__class__.__name__