Removing py.std usage from _pytest

This commit is contained in:
Bruno Oliveira 2014-07-31 19:13:40 -03:00
parent bcdc3d0154
commit 5603a0cd4b
16 changed files with 134 additions and 97 deletions

View File

@ -1,3 +1,5 @@
import traceback
import types
import py import py
import sys, inspect import sys, inspect
from compiler import parse, ast, pycodegen from compiler import parse, ast, pycodegen
@ -477,7 +479,7 @@ def check(s, frame=None):
def interpret(source, frame, should_fail=False): def interpret(source, frame, should_fail=False):
module = Interpretable(parse(source, 'exec').node) module = Interpretable(parse(source, 'exec').node)
#print "got module", module #print "got module", module
if isinstance(frame, py.std.types.FrameType): if isinstance(frame, types.FrameType):
frame = py.code.Frame(frame) frame = py.code.Frame(frame)
try: try:
module.run(frame) module.run(frame)
@ -487,7 +489,6 @@ def interpret(source, frame, should_fail=False):
except passthroughex: except passthroughex:
raise raise
except: except:
import traceback
traceback.print_exc() traceback.print_exc()
if should_fail: if should_fail:
return ("(assertion failed, but when it was re-run for " return ("(assertion failed, but when it was re-run for "

View File

@ -1,4 +1,5 @@
"""Utilities for assertion debugging""" """Utilities for assertion debugging"""
import pprint
import py import py
try: try:
@ -168,6 +169,7 @@ def _diff_text(left, right, verbose=False):
If the input are bytes they will be safely converted to text. If the input are bytes they will be safely converted to text.
""" """
from difflib import ndiff
explanation = [] explanation = []
if isinstance(left, py.builtin.bytes): if isinstance(left, py.builtin.bytes):
left = u(repr(left)[1:-1]).replace(r'\n', '\n') left = u(repr(left)[1:-1]).replace(r'\n', '\n')
@ -195,7 +197,7 @@ def _diff_text(left, right, verbose=False):
left = left[:-i] left = left[:-i]
right = right[:-i] right = right[:-i]
explanation += [line.strip('\n') explanation += [line.strip('\n')
for line in py.std.difflib.ndiff(left.splitlines(), for line in ndiff(left.splitlines(),
right.splitlines())] right.splitlines())]
return explanation return explanation
@ -214,8 +216,8 @@ def _compare_eq_sequence(left, right, verbose=False):
explanation += [ explanation += [
u('Right contains more items, first extra item: %s') % u('Right contains more items, first extra item: %s') %
py.io.saferepr(right[len(left)],)] py.io.saferepr(right[len(left)],)]
return explanation # + _diff_text(py.std.pprint.pformat(left), return explanation # + _diff_text(pprint.pformat(left),
# py.std.pprint.pformat(right)) # pprint.pformat(right))
def _compare_eq_set(left, right, verbose=False): def _compare_eq_set(left, right, verbose=False):
@ -242,7 +244,7 @@ def _compare_eq_dict(left, right, verbose=False):
len(same)] len(same)]
elif same: elif same:
explanation += [u('Common items:')] explanation += [u('Common items:')]
explanation += py.std.pprint.pformat(same).splitlines() explanation += pprint.pformat(same).splitlines()
diff = set(k for k in common if left[k] != right[k]) diff = set(k for k in common if left[k] != right[k])
if diff: if diff:
explanation += [u('Differing items:')] explanation += [u('Differing items:')]
@ -252,12 +254,12 @@ def _compare_eq_dict(left, right, verbose=False):
extra_left = set(left) - set(right) extra_left = set(left) - set(right)
if extra_left: if extra_left:
explanation.append(u('Left contains more items:')) explanation.append(u('Left contains more items:'))
explanation.extend(py.std.pprint.pformat( explanation.extend(pprint.pformat(
dict((k, left[k]) for k in extra_left)).splitlines()) dict((k, left[k]) for k in extra_left)).splitlines())
extra_right = set(right) - set(left) extra_right = set(right) - set(left)
if extra_right: if extra_right:
explanation.append(u('Right contains more items:')) explanation.append(u('Right contains more items:'))
explanation.extend(py.std.pprint.pformat( explanation.extend(pprint.pformat(
dict((k, right[k]) for k in extra_right)).splitlines()) dict((k, right[k]) for k in extra_right)).splitlines())
return explanation return explanation

View File

@ -1,4 +1,9 @@
""" command line options, ini-file and conftest.py processing. """ """ command line options, ini-file and conftest.py processing. """
import argparse
import shlex
import traceback
import types
import warnings
import py import py
# DON't import pytest here because it causes import cycle troubles # DON't import pytest here because it causes import cycle troubles
@ -29,7 +34,7 @@ def main(args=None, plugins=None):
except ConftestImportFailure: except ConftestImportFailure:
e = sys.exc_info()[1] e = sys.exc_info()[1]
tw = py.io.TerminalWriter(sys.stderr) tw = py.io.TerminalWriter(sys.stderr)
for line in py.std.traceback.format_exception(*e.excinfo): for line in traceback.format_exception(*e.excinfo):
tw.line(line.rstrip(), red=True) tw.line(line.rstrip(), red=True)
tw.line("ERROR: could not load %s\n" % (e.path), red=True) tw.line("ERROR: could not load %s\n" % (e.path), red=True)
return 4 return 4
@ -71,7 +76,7 @@ def _prepareconfig(args=None, plugins=None):
elif not isinstance(args, (tuple, list)): elif not isinstance(args, (tuple, list)):
if not isinstance(args, str): if not isinstance(args, str):
raise ValueError("not a string or argument list: %r" % (args,)) raise ValueError("not a string or argument list: %r" % (args,))
args = py.std.shlex.split(args) args = shlex.split(args)
pluginmanager = get_plugin_manager() pluginmanager = get_plugin_manager()
try: try:
if plugins: if plugins:
@ -229,7 +234,7 @@ class ArgumentError(Exception):
class Argument: class Argument:
"""class that mimics the necessary behaviour of py.std.optparse.Option """ """class that mimics the necessary behaviour of optparse.Option """
_typ_map = { _typ_map = {
'int': int, 'int': int,
'string': str, 'string': str,
@ -247,7 +252,7 @@ class Argument:
try: try:
help = attrs['help'] help = attrs['help']
if '%default' in help: if '%default' in help:
py.std.warnings.warn( warnings.warn(
'pytest now uses argparse. "%default" should be' 'pytest now uses argparse. "%default" should be'
' changed to "%(default)s" ', ' changed to "%(default)s" ',
FutureWarning, FutureWarning,
@ -263,7 +268,7 @@ class Argument:
if isinstance(typ, py.builtin._basestring): if isinstance(typ, py.builtin._basestring):
if typ == 'choice': if typ == 'choice':
if self.TYPE_WARN: if self.TYPE_WARN:
py.std.warnings.warn( warnings.warn(
'type argument to addoption() is a string %r.' 'type argument to addoption() is a string %r.'
' For parsearg this is optional and when supplied ' ' For parsearg this is optional and when supplied '
' should be a type.' ' should be a type.'
@ -275,7 +280,7 @@ class Argument:
attrs['type'] = type(attrs['choices'][0]) attrs['type'] = type(attrs['choices'][0])
else: else:
if self.TYPE_WARN: if self.TYPE_WARN:
py.std.warnings.warn( warnings.warn(
'type argument to addoption() is a string %r.' 'type argument to addoption() is a string %r.'
' For parsearg this should be a type.' ' For parsearg this should be a type.'
' (options: %s)' % (typ, names), ' (options: %s)' % (typ, names),
@ -395,10 +400,10 @@ class OptionGroup:
self.options.append(option) self.options.append(option)
class MyOptionParser(py.std.argparse.ArgumentParser): class MyOptionParser(argparse.ArgumentParser):
def __init__(self, parser): def __init__(self, parser):
self._parser = parser self._parser = parser
py.std.argparse.ArgumentParser.__init__(self, usage=parser._usage, argparse.ArgumentParser.__init__(self, usage=parser._usage,
add_help=False, formatter_class=DropShorterLongHelpFormatter) add_help=False, formatter_class=DropShorterLongHelpFormatter)
def parse_args(self, args=None, namespace=None): def parse_args(self, args=None, namespace=None):
@ -407,12 +412,12 @@ class MyOptionParser(py.std.argparse.ArgumentParser):
if argv: if argv:
for arg in argv: for arg in argv:
if arg and arg[0] == '-': if arg and arg[0] == '-':
msg = py.std.argparse._('unrecognized arguments: %s') msg = argparse._('unrecognized arguments: %s')
self.error(msg % ' '.join(argv)) self.error(msg % ' '.join(argv))
getattr(args, FILE_OR_DIR).extend(argv) getattr(args, FILE_OR_DIR).extend(argv)
return args return args
class DropShorterLongHelpFormatter(py.std.argparse.HelpFormatter): class DropShorterLongHelpFormatter(argparse.HelpFormatter):
"""shorten help for long options that differ only in extra hyphens """shorten help for long options that differ only in extra hyphens
- collapse **long** options that are the same except for extra hyphens - collapse **long** options that are the same except for extra hyphens
@ -422,7 +427,7 @@ class DropShorterLongHelpFormatter(py.std.argparse.HelpFormatter):
- cache result on action object as this is called at least 2 times - cache result on action object as this is called at least 2 times
""" """
def _format_action_invocation(self, action): def _format_action_invocation(self, action):
orgstr = py.std.argparse.HelpFormatter._format_action_invocation(self, action) orgstr = argparse.HelpFormatter._format_action_invocation(self, action)
if orgstr and orgstr[0] != '-': # only optional arguments if orgstr and orgstr[0] != '-': # only optional arguments
return orgstr return orgstr
res = getattr(action, '_formatted_action_invocation', None) res = getattr(action, '_formatted_action_invocation', None)
@ -746,7 +751,7 @@ class Config(object):
self.hook.pytest_cmdline_preparse(config=self, args=args) self.hook.pytest_cmdline_preparse(config=self, args=args)
args = self._parser.parse_setoption(args, self.option) args = self._parser.parse_setoption(args, self.option)
if not args: if not args:
args.append(py.std.os.getcwd()) args.append(os.getcwd())
self.args = args self.args = args
def addinivalue_line(self, name, line): def addinivalue_line(self, name, line):
@ -784,11 +789,11 @@ class Config(object):
if type == "pathlist": if type == "pathlist":
dp = py.path.local(self.inicfg.config.path).dirpath() dp = py.path.local(self.inicfg.config.path).dirpath()
l = [] l = []
for relpath in py.std.shlex.split(value): for relpath in shlex.split(value):
l.append(dp.join(relpath, abs=True)) l.append(dp.join(relpath, abs=True))
return l return l
elif type == "args": elif type == "args":
return py.std.shlex.split(value) return shlex.split(value)
elif type == "linelist": elif type == "linelist":
return [t for t in map(lambda x: x.strip(), value.split("\n")) if t] return [t for t in map(lambda x: x.strip(), value.split("\n")) if t]
else: else:
@ -876,7 +881,7 @@ def setns(obj, dic):
mod = getattr(obj, name, None) mod = getattr(obj, name, None)
if mod is None: if mod is None:
modname = "pytest.%s" % name modname = "pytest.%s" % name
mod = py.std.types.ModuleType(modname) mod = types.ModuleType(modname)
sys.modules[modname] = mod sys.modules[modname] = mod
mod.__all__ = [] mod.__all__ = []
setattr(obj, name, mod) setattr(obj, name, mod)

View File

@ -1,6 +1,7 @@
""" """
pytest PluginManager, basic initialization and tracing. pytest PluginManager, basic initialization and tracing.
""" """
import os
import sys import sys
import inspect import inspect
import py import py
@ -154,7 +155,7 @@ class PluginManager(object):
# API for bootstrapping # API for bootstrapping
# #
def _envlist(self, varname): def _envlist(self, varname):
val = py.std.os.environ.get(varname, None) val = os.environ.get(varname, None)
if val is not None: if val is not None:
return val.split(',') return val.split(',')
return () return ()
@ -221,7 +222,7 @@ class PluginManager(object):
return self.import_plugin(modname[7:]) return self.import_plugin(modname[7:])
raise raise
except: except:
e = py.std.sys.exc_info()[1] e = sys.exc_info()[1]
import pytest import pytest
if not hasattr(pytest, 'skip') or not isinstance(e, pytest.skip.Exception): if not hasattr(pytest, 'skip') or not isinstance(e, pytest.skip.Exception):
raise raise

View File

@ -1,5 +1,6 @@
""" discover and run doctests in modules and test files.""" """ discover and run doctests in modules and test files."""
from __future__ import absolute_import
import traceback
import pytest, py import pytest, py
from _pytest.python import FixtureRequest, FuncFixtureInfo from _pytest.python import FixtureRequest, FuncFixtureInfo
from py._code.code import TerminalRepr, ReprFileLocation from py._code.code import TerminalRepr, ReprFileLocation
@ -43,7 +44,7 @@ class DoctestItem(pytest.Item):
self.runner.run(self.dtest) self.runner.run(self.dtest)
def repr_failure(self, excinfo): def repr_failure(self, excinfo):
doctest = py.std.doctest import doctest
if excinfo.errisinstance((doctest.DocTestFailure, if excinfo.errisinstance((doctest.DocTestFailure,
doctest.UnexpectedException)): doctest.UnexpectedException)):
doctestfailure = excinfo.value doctestfailure = excinfo.value
@ -56,8 +57,8 @@ class DoctestItem(pytest.Item):
lineno = test.lineno + example.lineno + 1 lineno = test.lineno + example.lineno + 1
message = excinfo.type.__name__ message = excinfo.type.__name__
reprlocation = ReprFileLocation(filename, lineno, message) reprlocation = ReprFileLocation(filename, lineno, message)
checker = py.std.doctest.OutputChecker() checker = doctest.OutputChecker()
REPORT_UDIFF = py.std.doctest.REPORT_UDIFF REPORT_UDIFF = doctest.REPORT_UDIFF
filelines = py.path.local(filename).readlines(cr=0) filelines = py.path.local(filename).readlines(cr=0)
lines = [] lines = []
if lineno is not None: if lineno is not None:
@ -78,7 +79,7 @@ class DoctestItem(pytest.Item):
inner_excinfo = py.code.ExceptionInfo(excinfo.value.exc_info) inner_excinfo = py.code.ExceptionInfo(excinfo.value.exc_info)
lines += ["UNEXPECTED EXCEPTION: %s" % lines += ["UNEXPECTED EXCEPTION: %s" %
repr(inner_excinfo.value)] repr(inner_excinfo.value)]
lines += py.std.traceback.format_exception(*excinfo.value.exc_info) lines += traceback.format_exception(*excinfo.value.exc_info)
return ReprFailDoctest(reprlocation, lines) return ReprFailDoctest(reprlocation, lines)
else: else:
return super(DoctestItem, self).repr_failure(excinfo) return super(DoctestItem, self).repr_failure(excinfo)
@ -88,7 +89,7 @@ class DoctestItem(pytest.Item):
class DoctestTextfile(DoctestItem, pytest.File): class DoctestTextfile(DoctestItem, pytest.File):
def runtest(self): def runtest(self):
doctest = py.std.doctest import doctest
# satisfy `FixtureRequest` constructor... # satisfy `FixtureRequest` constructor...
self.funcargs = {} self.funcargs = {}
fm = self.session._fixturemanager fm = self.session._fixturemanager
@ -106,7 +107,7 @@ class DoctestTextfile(DoctestItem, pytest.File):
class DoctestModule(pytest.File): class DoctestModule(pytest.File):
def collect(self): def collect(self):
doctest = py.std.doctest import doctest
if self.fspath.basename == "conftest.py": if self.fspath.basename == "conftest.py":
module = self.config._conftest.importconftest(self.fspath) module = self.config._conftest.importconftest(self.fspath)
else: else:

View File

@ -1,9 +1,13 @@
""" generate a single-file self-contained version of pytest """ """ generate a single-file self-contained version of pytest """
import base64
import pickle
import py import py
import sys import sys
import zlib
def find_toplevel(name): def find_toplevel(name):
for syspath in py.std.sys.path: for syspath in sys.path:
base = py.path.local(syspath) base = py.path.local(syspath)
lib = base/name lib = base/name
if lib.check(dir=1): if lib.check(dir=1):
@ -29,9 +33,9 @@ def pkg_to_mapping(name):
return name2src return name2src
def compress_mapping(mapping): def compress_mapping(mapping):
data = py.std.pickle.dumps(mapping, 2) data = pickle.dumps(mapping, 2)
data = py.std.zlib.compress(data, 9) data = zlib.compress(data, 9)
data = py.std.base64.encodestring(data) data = base64.encodestring(data)
data = data.decode('ascii') data = data.decode('ascii')
return data return data

View File

@ -2,6 +2,7 @@
Based on initial code from Ross Lawley. Based on initial code from Ross Lawley.
""" """
import codecs
import py import py
import os import os
@ -206,8 +207,8 @@ class LogXML(object):
self.suite_start_time = time.time() self.suite_start_time = time.time()
def pytest_sessionfinish(self): def pytest_sessionfinish(self):
if py.std.sys.version_info[0] < 3: if sys.version_info[0] < 3:
logfile = py.std.codecs.open(self.logfile, 'w', encoding='utf-8') logfile = codecs.open(self.logfile, 'w', encoding='utf-8')
else: else:
logfile = open(self.logfile, 'w', encoding='utf-8') logfile = open(self.logfile, 'w', encoding='utf-8')

View File

@ -1,4 +1,5 @@
""" core implementation of testing process: init, session, runtest loop. """ """ core implementation of testing process: init, session, runtest loop. """
import re
import py import py
import pytest, _pytest import pytest, _pytest
@ -19,7 +20,7 @@ EXIT_INTERRUPTED = 2
EXIT_INTERNALERROR = 3 EXIT_INTERNALERROR = 3
EXIT_USAGEERROR = 4 EXIT_USAGEERROR = 4
name_re = py.std.re.compile("^[a-zA-Z_]\w*$") name_re = re.compile("^[a-zA-Z_]\w*$")
def pytest_addoption(parser): def pytest_addoption(parser):
parser.addini("norecursedirs", "directory patterns to avoid for recursion", parser.addini("norecursedirs", "directory patterns to avoid for recursion",
@ -315,7 +316,7 @@ class Node(object):
except py.builtin._sysex: except py.builtin._sysex:
raise raise
except: except:
failure = py.std.sys.exc_info() failure = sys.exc_info()
setattr(self, exattrname, failure) setattr(self, exattrname, failure)
raise raise
setattr(self, attrname, res) setattr(self, attrname, res)

View File

@ -1,8 +1,12 @@
""" interactive debugging with PDB, the Python Debugger. """ """ interactive debugging with PDB, the Python Debugger. """
from __future__ import absolute_import
import pytest, py import pdb
import sys import sys
import pytest
import py
def pytest_addoption(parser): def pytest_addoption(parser):
group = parser.getgroup("general") group = parser.getgroup("general")
group._addoption('--pdb', group._addoption('--pdb',
@ -16,10 +20,10 @@ def pytest_configure(config):
if config.getvalue("usepdb"): if config.getvalue("usepdb"):
config.pluginmanager.register(PdbInvoke(), 'pdbinvoke') config.pluginmanager.register(PdbInvoke(), 'pdbinvoke')
old = (py.std.pdb.set_trace, pytestPDB._pluginmanager) old = (pdb.set_trace, pytestPDB._pluginmanager)
def fin(): def fin():
py.std.pdb.set_trace, pytestPDB._pluginmanager = old pdb.set_trace, pytestPDB._pluginmanager = old
py.std.pdb.set_trace = pytest.set_trace pdb.set_trace = pytest.set_trace
pytestPDB._pluginmanager = config.pluginmanager pytestPDB._pluginmanager = config.pluginmanager
config._cleanup.append(fin) config._cleanup.append(fin)
@ -38,7 +42,7 @@ class pytestPDB:
tw = py.io.TerminalWriter() tw = py.io.TerminalWriter()
tw.line() tw.line()
tw.sep(">", "PDB set_trace (IO-capturing turned off)") tw.sep(">", "PDB set_trace (IO-capturing turned off)")
py.std.pdb.Pdb().set_trace(frame) pdb.Pdb().set_trace(frame)
class PdbInvoke: class PdbInvoke:
@ -74,7 +78,8 @@ def _enter_pdb(node, excinfo, rep):
def _postmortem_traceback(excinfo): def _postmortem_traceback(excinfo):
# A doctest.UnexpectedException is not useful for post_mortem. # A doctest.UnexpectedException is not useful for post_mortem.
# Use the underlying exception instead: # Use the underlying exception instead:
if isinstance(excinfo.value, py.std.doctest.UnexpectedException): from doctest import UnexpectedException
if isinstance(excinfo.value, UnexpectedException):
return excinfo.value.exc_info[2] return excinfo.value.exc_info[2]
else: else:
return excinfo._excinfo[2] return excinfo._excinfo[2]
@ -88,7 +93,6 @@ def _find_last_non_hidden_frame(stack):
def post_mortem(t): def post_mortem(t):
pdb = py.std.pdb
class Pdb(pdb.Pdb): class Pdb(pdb.Pdb):
def get_stack(self, f, t): def get_stack(self, f, t):
stack, i = pdb.Pdb.get_stack(self, f, t) stack, i = pdb.Pdb.get_stack(self, f, t)

View File

@ -1,15 +1,21 @@
""" (disabled by default) support for testing pytest and pytest plugins. """ """ (disabled by default) support for testing pytest and pytest plugins. """
import inspect
import py, pytest import sys
import sys, os import os
import codecs import codecs
import re import re
import time import time
import platform
from fnmatch import fnmatch from fnmatch import fnmatch
from _pytest.main import Session, EXIT_OK import subprocess
import py
import pytest
from py.builtin import print_ from py.builtin import print_
from _pytest.core import HookRelay from _pytest.core import HookRelay
from _pytest.main import Session, EXIT_OK
def get_public_names(l): def get_public_names(l):
"""Only return names from iterator l without a leading underscore.""" """Only return names from iterator l without a leading underscore."""
@ -87,10 +93,10 @@ class HookRecorder:
def _makecallparser(self, method): def _makecallparser(self, method):
name = method.__name__ name = method.__name__
args, varargs, varkw, default = py.std.inspect.getargspec(method) args, varargs, varkw, default = inspect.getargspec(method)
if not args or args[0] != "self": if not args or args[0] != "self":
args.insert(0, 'self') args.insert(0, 'self')
fspec = py.std.inspect.formatargspec(args, varargs, varkw, default) fspec = inspect.formatargspec(args, varargs, varkw, default)
# we use exec because we want to have early type # we use exec because we want to have early type
# errors on wrong input arguments, using # errors on wrong input arguments, using
# *args/**kwargs delays this and gives errors # *args/**kwargs delays this and gives errors
@ -122,7 +128,7 @@ class HookRecorder:
__tracebackhide__ = True __tracebackhide__ = True
i = 0 i = 0
entries = list(entries) entries = list(entries)
backlocals = py.std.sys._getframe(1).f_locals backlocals = sys._getframe(1).f_locals
while entries: while entries:
name, check = entries.pop(0) name, check = entries.pop(0)
for ind, call in enumerate(self.calls[i:]): for ind, call in enumerate(self.calls[i:]):
@ -210,7 +216,7 @@ class TmpTestdir:
def finalize(self): def finalize(self):
for p in self._syspathremove: for p in self._syspathremove:
py.std.sys.path.remove(p) sys.path.remove(p)
if hasattr(self, '_olddir'): if hasattr(self, '_olddir'):
self._olddir.chdir() self._olddir.chdir()
# delete modules that have been loaded from tmpdir # delete modules that have been loaded from tmpdir
@ -283,7 +289,7 @@ class TmpTestdir:
def syspathinsert(self, path=None): def syspathinsert(self, path=None):
if path is None: if path is None:
path = self.tmpdir path = self.tmpdir
py.std.sys.path.insert(0, str(path)) sys.path.insert(0, str(path))
self._syspathremove.append(str(path)) self._syspathremove.append(str(path))
def mkdir(self, name): def mkdir(self, name):
@ -426,8 +432,7 @@ class TmpTestdir:
env['PYTHONPATH'] = os.pathsep.join(filter(None, [ env['PYTHONPATH'] = os.pathsep.join(filter(None, [
str(os.getcwd()), env.get('PYTHONPATH', '')])) str(os.getcwd()), env.get('PYTHONPATH', '')]))
kw['env'] = env kw['env'] = env
#print "env", env return subprocess.Popen(cmdargs,
return py.std.subprocess.Popen(cmdargs,
stdout=stdout, stderr=stderr, **kw) stdout=stdout, stderr=stderr, **kw)
def run(self, *cmdargs): def run(self, *cmdargs):
@ -474,9 +479,9 @@ class TmpTestdir:
def _getpybinargs(self, scriptname): def _getpybinargs(self, scriptname):
if not self.request.config.getvalue("notoolsonpath"): if not self.request.config.getvalue("notoolsonpath"):
# XXX we rely on script referring to the correct environment # XXX we rely on script referring to the correct environment
# we cannot use "(py.std.sys.executable,script)" # we cannot use "(sys.executable,script)"
# because on windows the script is e.g. a py.test.exe # because on windows the script is e.g. a py.test.exe
return (py.std.sys.executable, _pytest_fullpath,) # noqa return (sys.executable, _pytest_fullpath,) # noqa
else: else:
pytest.skip("cannot run %r with --no-tools-on-path" % scriptname) pytest.skip("cannot run %r with --no-tools-on-path" % scriptname)
@ -496,7 +501,7 @@ class TmpTestdir:
def runpython_c(self, command): def runpython_c(self, command):
command = self._getsysprepend() + command command = self._getsysprepend() + command
return self.run(py.std.sys.executable, "-c", command) return self.run(sys.executable, "-c", command)
def runpytest(self, *args): def runpytest(self, *args):
p = py.path.local.make_numbered_dir(prefix="runpytest-", p = py.path.local.make_numbered_dir(prefix="runpytest-",
@ -523,7 +528,7 @@ class TmpTestdir:
def spawn(self, cmd, expect_timeout=10.0): def spawn(self, cmd, expect_timeout=10.0):
pexpect = pytest.importorskip("pexpect", "3.0") pexpect = pytest.importorskip("pexpect", "3.0")
if hasattr(sys, 'pypy_version_info') and '64' in py.std.platform.machine(): if hasattr(sys, 'pypy_version_info') and '64' in platform.machine():
pytest.skip("pypy-64 bit not supported") pytest.skip("pypy-64 bit not supported")
if sys.platform == "darwin": if sys.platform == "darwin":
pytest.xfail("pexpect does not work reliably on darwin?!") pytest.xfail("pexpect does not work reliably on darwin?!")
@ -670,7 +675,7 @@ class LineMatcher:
def fnmatch_lines(self, lines2): def fnmatch_lines(self, lines2):
def show(arg1, arg2): def show(arg1, arg2):
py.builtin.print_(arg1, arg2, file=py.std.sys.stderr) py.builtin.print_(arg1, arg2, file=sys.stderr)
lines2 = self._getlines(lines2) lines2 = self._getlines(lines2)
lines1 = self.lines[:] lines1 = self.lines[:]
nextline = None nextline = None

View File

@ -1,7 +1,8 @@
""" recording warnings during test function execution. """ """ recording warnings during test function execution. """
import py
import sys import sys
import warnings
def pytest_funcarg__recwarn(request): def pytest_funcarg__recwarn(request):
"""Return a WarningsRecorder instance that provides these methods: """Return a WarningsRecorder instance that provides these methods:
@ -13,7 +14,6 @@ def pytest_funcarg__recwarn(request):
on warning categories. on warning categories.
""" """
if sys.version_info >= (2,7): if sys.version_info >= (2,7):
import warnings
oldfilters = warnings.filters[:] oldfilters = warnings.filters[:]
warnings.simplefilter('default') warnings.simplefilter('default')
def reset_filters(): def reset_filters():
@ -30,26 +30,24 @@ def deprecated_call(func, *args, **kwargs):
""" assert that calling ``func(*args, **kwargs)`` """ assert that calling ``func(*args, **kwargs)``
triggers a DeprecationWarning. triggers a DeprecationWarning.
""" """
warningmodule = py.std.warnings
l = [] l = []
oldwarn_explicit = getattr(warningmodule, 'warn_explicit') oldwarn_explicit = getattr(warnings, 'warn_explicit')
def warn_explicit(*args, **kwargs): def warn_explicit(*args, **kwargs):
l.append(args) l.append(args)
oldwarn_explicit(*args, **kwargs) oldwarn_explicit(*args, **kwargs)
oldwarn = getattr(warningmodule, 'warn') oldwarn = getattr(warnings, 'warn')
def warn(*args, **kwargs): def warn(*args, **kwargs):
l.append(args) l.append(args)
oldwarn(*args, **kwargs) oldwarn(*args, **kwargs)
warningmodule.warn_explicit = warn_explicit warnings.warn_explicit = warn_explicit
warningmodule.warn = warn warnings.warn = warn
try: try:
ret = func(*args, **kwargs) ret = func(*args, **kwargs)
finally: finally:
warningmodule.warn_explicit = warn_explicit warnings.warn_explicit = warn_explicit
warningmodule.warn = warn warnings.warn = warn
if not l: if not l:
#print warningmodule
__tracebackhide__ = True __tracebackhide__ = True
raise AssertionError("%r did not produce DeprecationWarning" %(func,)) raise AssertionError("%r did not produce DeprecationWarning" %(func,))
return ret return ret
@ -65,7 +63,6 @@ class RecordedWarning:
class WarningsRecorder: class WarningsRecorder:
def __init__(self): def __init__(self):
warningmodule = py.std.warnings
self.list = [] self.list = []
def showwarning(message, category, filename, lineno, line=0): def showwarning(message, category, filename, lineno, line=0):
self.list.append(RecordedWarning( self.list.append(RecordedWarning(
@ -76,8 +73,8 @@ class WarningsRecorder:
except TypeError: except TypeError:
# < python2.6 # < python2.6
self.old_showwarning(message, category, filename, lineno) self.old_showwarning(message, category, filename, lineno)
self.old_showwarning = warningmodule.showwarning self.old_showwarning = warnings.showwarning
warningmodule.showwarning = showwarning warnings.showwarning = showwarning
def pop(self, cls=Warning): def pop(self, cls=Warning):
""" pop the first recorded warning, raise exception if not exists.""" """ pop the first recorded warning, raise exception if not exists."""
@ -88,7 +85,6 @@ class WarningsRecorder:
assert 0, "%r not found in %r" %(cls, self.list) assert 0, "%r not found in %r" %(cls, self.list)
#def resetregistry(self): #def resetregistry(self):
# import warnings
# warnings.onceregistry.clear() # warnings.onceregistry.clear()
# warnings.__warningregistry__.clear() # warnings.__warningregistry__.clear()
@ -96,4 +92,4 @@ class WarningsRecorder:
self.list[:] = [] self.list[:] = []
def finalize(self): def finalize(self):
py.std.warnings.showwarning = self.old_showwarning warnings.showwarning = self.old_showwarning

View File

@ -1,9 +1,10 @@
""" basic collect and runtest protocol implementations """ """ basic collect and runtest protocol implementations """
import bdb
import sys
from time import time
import py import py
import pytest import pytest
import sys
from time import time
from py._code.code import TerminalRepr from py._code.code import TerminalRepr
def pytest_namespace(): def pytest_namespace():
@ -118,7 +119,7 @@ def check_interactive_exception(call, report):
return call.excinfo and not ( return call.excinfo and not (
hasattr(report, "wasxfail") or hasattr(report, "wasxfail") or
call.excinfo.errisinstance(skip.Exception) or call.excinfo.errisinstance(skip.Exception) or
call.excinfo.errisinstance(py.std.bdb.BdbQuit)) call.excinfo.errisinstance(bdb.BdbQuit))
def call_runtest_hook(item, when, **kwds): def call_runtest_hook(item, when, **kwds):
hookname = "pytest_runtest_" + when hookname = "pytest_runtest_" + when

View File

@ -1,7 +1,10 @@
""" support for skip/xfail functions and markers. """ """ support for skip/xfail functions and markers. """
import os
import py, pytest
import sys import sys
import traceback
import py
import pytest
def pytest_addoption(parser): def pytest_addoption(parser):
group = parser.getgroup("general") group = parser.getgroup("general")
@ -79,7 +82,7 @@ class MarkEvaluator:
msg = [" " * (self.exc[1].offset + 4) + "^",] msg = [" " * (self.exc[1].offset + 4) + "^",]
msg.append("SyntaxError: invalid syntax") msg.append("SyntaxError: invalid syntax")
else: else:
msg = py.std.traceback.format_exception_only(*self.exc[:2]) msg = traceback.format_exception_only(*self.exc[:2])
pytest.fail("Error evaluating %r expression\n" pytest.fail("Error evaluating %r expression\n"
" %s\n" " %s\n"
"%s" "%s"
@ -87,7 +90,7 @@ class MarkEvaluator:
pytrace=False) pytrace=False)
def _getglobals(self): def _getglobals(self):
d = {'os': py.std.os, 'sys': py.std.sys, 'config': self.item.config} d = {'os': os, 'sys': sys, 'config': self.item.config}
func = self.item.obj func = self.item.obj
try: try:
d.update(func.__globals__) d.update(func.__globals__)

View File

@ -5,6 +5,8 @@ This is a good source for looking at the various reporting hooks.
import pytest import pytest
import py import py
import sys import sys
import time
def pytest_addoption(parser): def pytest_addoption(parser):
group = parser.getgroup("terminal reporting", "reporting", after="general") group = parser.getgroup("terminal reporting", "reporting", after="general")
@ -49,7 +51,7 @@ def getreportopt(config):
optvalue = config.option.report optvalue = config.option.report
if optvalue: if optvalue:
py.builtin.print_("DEPRECATED: use -r instead of --report option.", py.builtin.print_("DEPRECATED: use -r instead of --report option.",
file=py.std.sys.stderr) file=sys.stderr)
if optvalue: if optvalue:
for setting in optvalue.split(","): for setting in optvalue.split(","):
setting = setting.strip() setting = setting.strip()
@ -95,7 +97,7 @@ class TerminalReporter:
self.stats = {} self.stats = {}
self.startdir = self.curdir = py.path.local() self.startdir = self.curdir = py.path.local()
if file is None: if file is None:
file = py.std.sys.stdout file = sys.stdout
self._tw = self.writer = py.io.TerminalWriter(file) self._tw = self.writer = py.io.TerminalWriter(file)
if self.config.option.color == 'yes': if self.config.option.color == 'yes':
self._tw.hasmarkup = True self._tw.hasmarkup = True
@ -265,7 +267,7 @@ class TerminalReporter:
@pytest.mark.trylast @pytest.mark.trylast
def pytest_sessionstart(self, session): def pytest_sessionstart(self, session):
self._sessionstarttime = py.std.time.time() self._sessionstarttime = time.time()
if not self.showheader: if not self.showheader:
return return
self.write_sep("=", "test session starts", bold=True) self.write_sep("=", "test session starts", bold=True)
@ -469,7 +471,7 @@ class TerminalReporter:
self._tw.line(content) self._tw.line(content)
def summary_stats(self): def summary_stats(self):
session_duration = py.std.time.time() - self._sessionstarttime session_duration = time.time() - self._sessionstarttime
keys = ("failed passed skipped deselected " keys = ("failed passed skipped deselected "
"xfailed xpassed warnings").split() "xfailed xpassed warnings").split()

View File

@ -1,7 +1,11 @@
""" support for providing temporary directories to test functions. """ """ support for providing temporary directories to test functions. """
import pytest, py import re
import pytest
import py
from _pytest.monkeypatch import monkeypatch from _pytest.monkeypatch import monkeypatch
class TempdirHandler: class TempdirHandler:
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
@ -63,7 +67,7 @@ def tmpdir(request):
path object. path object.
""" """
name = request.node.name name = request.node.name
name = py.std.re.sub("[\W]", "_", name) name = re.sub("[\W]", "_", name)
MAXVAL = 30 MAXVAL = 30
if len(name) > MAXVAL: if len(name) > MAXVAL:
name = name[:MAXVAL] name = name[:MAXVAL]

View File

@ -1,7 +1,13 @@
""" discovery and running of std-library "unittest" style tests. """ """ discovery and running of std-library "unittest" style tests. """
import pytest, py from __future__ import absolute_import
import traceback
import unittest
import sys import sys
import pytest
import py
# for transfering markers # for transfering markers
from _pytest.python import transfer_markers from _pytest.python import transfer_markers
@ -45,7 +51,7 @@ class UnitTestCase(pytest.Class):
if not getattr(cls, "__test__", True): if not getattr(cls, "__test__", True):
return return
self.session._fixturemanager.parsefactories(self, unittest=True) self.session._fixturemanager.parsefactories(self, unittest=True)
loader = py.std.unittest.TestLoader() loader = unittest.TestLoader()
module = self.getparent(pytest.Module).obj module = self.getparent(pytest.Module).obj
foundsomething = False foundsomething = False
for name in loader.getTestCaseNames(self.obj): for name in loader.getTestCaseNames(self.obj):
@ -90,7 +96,7 @@ class TestCaseFunction(pytest.Function):
except TypeError: except TypeError:
try: try:
try: try:
l = py.std.traceback.format_exception(*rawexcinfo) l = traceback.format_exception(*rawexcinfo)
l.insert(0, "NOTE: Incompatible Exception Representation, " l.insert(0, "NOTE: Incompatible Exception Representation, "
"displaying natively:\n\n") "displaying natively:\n\n")
pytest.fail("".join(l), pytrace=False) pytest.fail("".join(l), pytrace=False)