def test_GeneratorExit():
assert py.builtin.GeneratorExit.__module__ in ('exceptions', 'builtins')
assert issubclass(py.builtin.GeneratorExit, py.builtin.BaseException)
python类builtin()的实例源码
def test_reversed():
reversed = py.builtin.reversed
r = reversed("hello")
assert iter(r) is r
s = "".join(list(r))
assert s == "olleh"
assert list(reversed(list(reversed("hello")))) == ['h','e','l','l','o']
py.test.raises(TypeError, reversed, reversed("hello"))
def test_execfile(tmpdir):
test_file = tmpdir.join("test.py")
test_file.write("x = y\ndef f(): pass")
ns = {"y" : 42}
py.builtin.execfile(str(test_file), ns)
assert ns["x"] == 42
assert py.code.getrawcode(ns["f"]).co_filename == str(test_file)
class A:
y = 3
x = 4
py.builtin.execfile(str(test_file))
assert A.x == 3
def test_getfuncdict():
def f():
pass
f.x = 4
assert py.builtin._getfuncdict(f)["x"] == 4
assert py.builtin._getfuncdict(2) is None
def test_callable():
class A: pass
assert py.builtin.callable(test_callable)
assert py.builtin.callable(A)
assert py.builtin.callable(list)
assert py.builtin.callable(id)
assert not py.builtin.callable(4)
assert not py.builtin.callable("hi")
def test_totext():
py.builtin._totext("hello", "UTF-8")
def test_totext_badutf8():
# this was in printouts within the pytest testsuite
# totext would fail
if sys.version_info >= (3,):
errors = 'surrogateescape'
else: # old python has crappy error handlers
errors = 'replace'
py.builtin._totext("\xa6", "UTF-8", errors)
def test_reraise():
from py.builtin import _reraise
try:
raise Exception()
except Exception:
cls, val, tb = sys.exc_info()
excinfo = py.test.raises(Exception, "_reraise(cls, val, tb)")
def test_exec():
l = []
py.builtin.exec_("l.append(1)")
assert l == [1]
d = {}
py.builtin.exec_("x=4", d)
assert d['x'] == 4
def test_tryimport():
py.test.raises(ImportError, py.builtin._tryimport, 'xqwe123')
x = py.builtin._tryimport('asldkajsdl', 'py')
assert x == py
x = py.builtin._tryimport('asldkajsdl', 'py.path')
assert x == py.path
def test_getcode():
code = py.builtin._getcode(test_getcode)
assert isinstance(code, types.CodeType)
assert py.builtin._getcode(4) is None
def test_capturing_readouterr_decode_error_handling(self):
with self.getcapture() as cap:
# triggered a internal error in pytest
print('\xa6')
out, err = cap.readouterr()
assert out == py.builtin._totext('\ufffd\n', 'unicode-escape')
def _dump_lines(self, lines, fp):
try:
for line in lines:
py.builtin.print_(line, file=fp)
except UnicodeEncodeError:
print("couldn't print to %s because of encoding" % (fp,))
def fnmatch_lines(self, lines2):
"""Search the text for matching lines.
The argument is a list of lines which have to match and can
use glob wildcards. If they do not match an pytest.fail() is
called. The matches and non-matches are also printed on
stdout.
"""
def show(arg1, arg2):
py.builtin.print_(arg1, arg2, file=sys.stderr)
lines2 = self._getlines(lines2)
lines1 = self.lines[:]
nextline = None
extralines = []
__tracebackhide__ = True
for line in lines2:
nomatchprinted = False
while lines1:
nextline = lines1.pop(0)
if line == nextline:
show("exact match:", repr(line))
break
elif fnmatch(nextline, line):
show("fnmatch:", repr(line))
show(" with:", repr(nextline))
break
else:
if not nomatchprinted:
show("nomatch:", repr(line))
nomatchprinted = True
show(" and:", repr(nextline))
extralines.append(nextline)
else:
pytest.fail("remains unmatched: %r, see stderr" % (line,))
def test_capturing_readouterr_unicode(self):
cap = self.getcapture()
print ("hx\xc4\x85\xc4\x87")
out, err = cap.readouterr()
assert out == py.builtin._totext("hx\xc4\x85\xc4\x87\n", "utf8")
def test_capturing_readouterr_decode_error_handling(self):
cap = self.getcapture()
# triggered a internal error in pytest
print('\xa6')
out, err = cap.readouterr()
assert out == py.builtin._totext('\ufffd\n', 'unicode-escape')
def test_any():
assert not py.builtin.any([0,False, None])
assert py.builtin.any([0,False, None,1])
def test_BaseException():
assert issubclass(IndexError, py.builtin.BaseException)
assert issubclass(Exception, py.builtin.BaseException)
assert issubclass(KeyboardInterrupt, py.builtin.BaseException)
class MyRandomClass(object):
pass
assert not issubclass(MyRandomClass, py.builtin.BaseException)
assert py.builtin.BaseException.__module__ in ('exceptions', 'builtins')
assert Exception.__name__ == 'Exception'
def test_GeneratorExit():
assert py.builtin.GeneratorExit.__module__ in ('exceptions', 'builtins')
assert issubclass(py.builtin.GeneratorExit, py.builtin.BaseException)
def test_reversed():
reversed = py.builtin.reversed
r = reversed("hello")
assert iter(r) is r
s = "".join(list(r))
assert s == "olleh"
assert list(reversed(list(reversed("hello")))) == ['h','e','l','l','o']
py.test.raises(TypeError, reversed, reversed("hello"))