[py-svn] r51483 - in py/branch/event/py/test2: . testing

hpk at codespeak.net hpk at codespeak.net
Thu Feb 14 12:24:21 CET 2008


Author: hpk
Date: Thu Feb 14 12:24:20 2008
New Revision: 51483

Added:
   py/branch/event/py/test2/present.py
      - copied, changed from r51481, py/branch/event/py/test2/representation.py
   py/branch/event/py/test2/testing/test_present.py
      - copied, changed from r51481, py/branch/event/py/test2/testing/test_repr.py
Removed:
   py/branch/event/py/test2/representation.py
   py/branch/event/py/test2/testing/test_repr.py
Modified:
   py/branch/event/py/test2/repevent.py
   py/branch/event/py/test2/reporter.py
Log:
bit of renaming and refactoring of presentation tests (much more to do there, sigh) 


Copied: py/branch/event/py/test2/present.py (from r51481, py/branch/event/py/test2/representation.py)
==============================================================================
--- py/branch/event/py/test2/representation.py	(original)
+++ py/branch/event/py/test2/present.py	Thu Feb 14 12:24:20 2008
@@ -34,6 +34,13 @@
             return ".".join(parts)
     return colitem.name  
 
+def repr_pythonversion():
+    v = py.std.sys.version_info
+    try:
+        return "%s.%s.%s-%s-%s" % v
+    except (TypeError, ValueError):
+        return str(v)
+
 class Presenter(object):
     """ Class used for presentation of various objects,
     sharing common output style
@@ -203,10 +210,3 @@
     # the following is only used by the combination '--pdb --tb=no'
     repr_failure_tbno = repr_failure_tbshort
 
-
-def repr_pythonversion():
-    v = py.std.sys.version_info
-    try:
-        return "%s.%s.%s-%s-%s" % v
-    except ValueError:
-        return str(v)

Modified: py/branch/event/py/test2/repevent.py
==============================================================================
--- py/branch/event/py/test2/repevent.py	(original)
+++ py/branch/event/py/test2/repevent.py	Thu Feb 14 12:24:20 2008
@@ -73,7 +73,7 @@
 
     def dottedpath(self, config):
         """ return dotted path for underlying test item. """ 
-        from py.__.test2.representation import getmodpath 
+        from py.__.test2.present import getmodpath 
         col = config._getcollector(self.trail) 
         return getmodpath(col) 
 

Modified: py/branch/event/py/test2/reporter.py
==============================================================================
--- py/branch/event/py/test2/reporter.py	(original)
+++ py/branch/event/py/test2/reporter.py	Thu Feb 14 12:24:20 2008
@@ -11,7 +11,7 @@
 from py.__.test2 import repevent
 from py.__.test2 import outcome
 from py.__.misc.terminal_helper import ansi_print, get_terminal_width
-from py.__.test2.representation import Presenter, repr_pythonversion,\
+from py.__.test2.present import Presenter, repr_pythonversion,\
      getrelpath
 
 import sys

Deleted: /py/branch/event/py/test2/representation.py
==============================================================================
--- /py/branch/event/py/test2/representation.py	Thu Feb 14 12:24:20 2008
+++ (empty file)
@@ -1,212 +0,0 @@
-
-""" This file intends to gather all methods of representing
-failures/tracebacks etc. which should be used among
-all terminal-based reporters. This methods should be general,
-to allow further use outside the pylib
-"""
-
-import py
-from py.__.code import safe_repr
-
-def getrelpath(source, dest): 
-    base = source.common(dest)
-    if not base: 
-        return None 
-    # with posix local paths '/' is always a common base
-    relsource = source.relto(base)
-    reldest = dest.relto(base)
-    n = relsource.count(source.sep)
-    target = dest.sep.join(('..', )*n + (reldest, ))
-    return target 
-
-def getmodpath(pycolitem): 
-    """ return dotted module path for the given colitem. """ 
-    colitems = pycolitem.listchain()
-    while colitems: 
-        colitem = colitems.pop(0)
-        if isinstance(colitem, colitem.Module):
-            parts = [colitem.obj.__name__]
-            for colitem in colitems: 
-                if colitem.name[0] in '([':
-                    parts[-1] += colitem.name 
-                else:
-                    parts.append(colitem.name) 
-            return ".".join(parts)
-    return colitem.name  
-
-class Presenter(object):
-    """ Class used for presentation of various objects,
-    sharing common output style
-    """
-    def __init__(self, out, config):
-        """ out is a file-like object (we can write to it)
-        """
-        assert hasattr(out, 'write')
-        self.out = out
-        self.config = config
-
-    def repr_source(self, source, marker=">", marker_location=-1):
-        """ This one represents piece of source with possible
-        marker at requested position
-        """
-        if isinstance(source, str):
-            # why the hell, string is iterable?
-            source = source.split("\n")
-        if marker_location < 0:
-            marker_location += len(source)
-            if marker_location < 0:
-                marker_location = 0
-        if marker_location >= len(source):
-            marker_location = len(source) - 1
-        for i in range(len(source)):
-            if i == marker_location:
-                prefix = marker + "   "
-            else:
-                prefix = "    "
-            self.out.line(prefix + source[i])
-
-    def repr_item_info(self, item):
-        """ This method represents py.test2.collect.Item info (path and module)
-        """
-        root = item.fspath 
-        modpath = item._getmodpath() 
-        try: 
-            fn, lineno = item._getpathlineno() 
-        except TypeError: 
-            assert isinstance(item.parent, py.test2.collect.Generator) 
-            # a generative test yielded a non-callable 
-            fn, lineno = item.parent._getpathlineno() 
-        if root == fn:
-            self.out.sep("_", "entrypoint: %s" %(modpath))
-        else:
-            self.out.sep("_", "entrypoint: %s %s" %(root.basename, modpath))
-
-    def repr_failure_explanation(self, excinfo, source):
-        try:
-            s = str(source.getstatement(len(source)-1))
-        except KeyboardInterrupt: 
-            raise 
-        except: 
-            s = str(source[-1])
-        indent = " " * (4 + (len(s) - len(s.lstrip())))
-        # get the real exception information out 
-        lines = excinfo.exconly(tryshort=True).split('\n')
-        self.out.line('>' + indent[:-1] + lines.pop(0))
-        for x in lines:
-            self.out.line(indent + x)
-
-    def getentrysource(self, entry):
-        try:
-            source = entry.getsource()
-        except py.error.ENOENT:
-            source = py.code.Source("[failure to get at sourcelines from %r]\n" % entry)
-        return source.deindent()
-
-    def repr_locals(self, f_locals):
-        if self.config.option.showlocals:
-            self.out.sep('- ', 'locals')
-            for name, value in f_locals.items():
-                if name == '__builtins__': 
-                    self.out.line("__builtins__ = <builtins>")
-                else:
-                    # This formatting could all be handled by the _repr() function, which is 
-                    # only repr.Repr in disguise, so is very configurable.
-                    str_repr = safe_repr._repr(value)
-                    if len(str_repr) < 70 or not isinstance(value,
-                                                (list, tuple, dict)):
-                        self.out.line("%-10s = %s" %(name, str_repr))
-                    else:
-                        self.out.line("%-10s =\\" % (name,))
-                        py.std.pprint.pprint(value, stream=self.out)
-
-    def repr_failure_tblong(self, item, excinfo, traceback, out_err_reporter):
-        if not self.config.option.nomagic and excinfo.errisinstance(RuntimeError):
-            recursionindex = traceback.recursionindex()
-        else:
-            recursionindex = None
-        last = traceback[-1]
-        first = traceback[0]
-        for index, entry in py.builtin.enumerate(traceback): 
-            if entry == first:
-                if item: 
-                    self.repr_item_info(item) 
-                    self.out.line()
-            else: 
-                self.out.line("")
-            source = self.getentrysource(entry)
-            firstsourceline = entry.getfirstlinesource()
-            marker_location = entry.lineno - firstsourceline
-            if entry == last: 
-                self.repr_source(source, 'E', marker_location)
-                self.repr_failure_explanation(excinfo, source) 
-            else:
-                self.repr_source(source, '>', marker_location)
-            self.out.line("") 
-            self.out.line("[%s:%d]" %(entry.path, entry.lineno+1))
-            self.repr_locals(entry.locals)
-
-            # trailing info 
-            if entry == last:
-                out_err_reporter() 
-                self.out.sep("_")
-            else: 
-                self.out.sep("_ ")
-                if index == recursionindex:
-                    self.out.line("Recursion detected (same locals & position)")
-                    self.out.sep("!")
-                    break
-
-    def repr_failure_tbshort(self, item, excinfo, traceback, out_err_reporter):
-        # print a Python-style short traceback
-        if not self.config.option.nomagic and excinfo.errisinstance(RuntimeError):
-            recursionindex = traceback.recursionindex()
-        else:
-            recursionindex = None
-        last = traceback[-1]
-        first = traceback[0]
-        self.out.line()
-        for index, entry in py.builtin.enumerate(traceback):
-            path = entry.path.basename
-            firstsourceline = entry.getfirstlinesource()
-            relline = entry.lineno - firstsourceline
-            self.out.line('  File "%s", line %d, in %s' % (
-                path, entry.lineno+1, entry.name))
-            try:
-                source = entry.getsource().lines
-            except py.error.ENOENT:
-                source = ["?"]
-            else:
-                try:
-                    if len(source) > 1:
-                        source = source[relline]
-                except IndexError:
-                    source = []
-            if entry == last:
-                if source:
-                    self.repr_source(source, 'E')
-                self.repr_failure_explanation(excinfo, source) 
-            else:
-                if source:
-                    self.repr_source(source, ' ')
-            self.repr_locals(entry.locals) 
-
-            # trailing info 
-            if entry == last:
-                out_err_reporter()
-                self.out.sep("_")
-            else: 
-                if index == recursionindex:
-                    self.out.line("Recursion detected (same locals & position)")
-                    self.out.sep("!")
-                    break 
-
-    # the following is only used by the combination '--pdb --tb=no'
-    repr_failure_tbno = repr_failure_tbshort
-
-
-def repr_pythonversion():
-    v = py.std.sys.version_info
-    try:
-        return "%s.%s.%s-%s-%s" % v
-    except ValueError:
-        return str(v)

Copied: py/branch/event/py/test2/testing/test_present.py (from r51481, py/branch/event/py/test2/testing/test_repr.py)
==============================================================================
--- py/branch/event/py/test2/testing/test_repr.py	(original)
+++ py/branch/event/py/test2/testing/test_present.py	Thu Feb 14 12:24:20 2008
@@ -1,9 +1,8 @@
 
 import py
-from py.__.test2.representation import Presenter, getmodpath
+from py.__.test2 import present, repevent
 from py.__.test2.terminal.out import getout
-from StringIO import StringIO
-import setupdata
+import suptest, setupdata
 import sys
 
 def test_getmodpath_cases():
@@ -13,10 +12,10 @@
     nopkgdir = tmpdir.ensure("nopkg", dir=1) 
     def checkpkg(names, expected):
         fcol = setupdata.getexamplecollector(names, tmpdir=pkgdir)
-        assert getmodpath(fcol) == pkgdir.basename + "." + expected 
+        assert present.getmodpath(fcol) == pkgdir.basename + "." + expected 
     def checknopkg(names, expected):
         fcol = setupdata.getexamplecollector(names, tmpdir=nopkgdir)
-        assert getmodpath(fcol) == expected 
+        assert present.getmodpath(fcol) == expected 
 
     for names in (
         'mod.py test_f1           mod.test_f1', 
@@ -29,66 +28,87 @@
         yield checkpkg, names, expected 
         yield checknopkg, names, expected 
 
-def newconfig(*args):
-    tmpdir = py.test2.ensuretemp("newconfig")
-    args = list(args)
-    args.append(tmpdir)
-    return py.test2.config._reparse(args)
+def test_repr_python_version():
+    py.magic.patch(py.std.sys, 'version_info', (2, 5, 1, 'final', 0))
+    try:
+        assert present.repr_pythonversion() == "2.5.1-final-0"
+        py.std.sys.version_info = x = (2,3)
+        assert present.repr_pythonversion() == str(x) 
+    finally: 
+        py.magic.revert(py.std.sys, 'version_info') 
+
+class TestPresenter: 
+    def setup_class(cls):
+        cls.tmpdir = py.test2.ensuretemp(cls.__name__) 
+
+    def getconfig(self, args=()):
+        return py.test2.config._reparse([self.tmpdir] + list(args))
+
+    def getpresenter(self, cmdlinearg=""):
+        config = self.getconfig(cmdlinearg.split())
+        stringio = py.std.StringIO.StringIO()
+        out = getout(stringio)
+        p = present.Presenter(out, config)
+        p.stringio = stringio 
+        return p
+
+    def test_repr_source(self):
+        source = py.code.Source("""
+            def f(x):
+                pass
+        """).strip()
+        p = self.getpresenter()
+        p.repr_source(source, "|", 0)
+        lines = p.stringio.getvalue().split("\n")
+        assert len(lines) == 3
+        assert lines[0].startswith("|")
+        assert lines[0].find("def f(x)") != -1
+        assert lines[1].find("pass") != -1
+
+    def test_repr_failure_explanation(self):
+        """ check if indentation is right """
+        def f():
+            def g():
+                1/0
+            try:
+                g()
+            except:
+                e = py.code.ExceptionInfo()
+            return e
     
-def test_repr_source():
-    source = py.code.Source("""
-    def f(x):
-        pass
-    """).strip()
-    config = newconfig()
-    s = StringIO()
-    out = getout(s)
-    p = Presenter(out, config)
-    p.repr_source(source, "|", 0)
-    lines = s.getvalue().split("\n")
-    assert len(lines) == 3
-    assert lines[0].startswith("|")
-    assert lines[0].find("def f(x)") != -1
-    assert lines[1].find("pass") != -1
-
-def test_repr_failure_explanation():
-    """ We check here if indentation is right
-    """
-    def f():
-        def g():
-            1/0
-        try:
-            g()
-        except:
-            e = py.code.ExceptionInfo()
-        return e
-    config = newconfig()
-    s = StringIO()
-    out = getout(s)
-    p = Presenter(out, config)
-    source = py.code.Source(f)
-    e = f()
-    p.repr_failure_explanation(e, source)
-    assert s.getvalue().startswith(">   ")
-
-def test_repr_local():
-    config = newconfig('--showlocals')
-    s = StringIO()
-    out = getout(s)
-    p = Presenter(out, config)
-    p.repr_locals(locals())
-    for key in locals().keys():
-        assert s.getvalue().find(key) != -1
-
-def XXXtest_repr_traceback_long():
-    py.test.skip("unfinished")
-    config = py.test2.config._reparse([])
-    s = StringIO()
-    out = getout(s)
-    p = Presenter(out, config)
-    # errr... here we should
-    # a) prepare an item
-    # b) prepare excinfo
-    # c) prepare some traceback info, with few different ideas,
-    #    like recursion detected etc.
-    # test it...
+        p = self.getpresenter()
+        source = py.code.Source(f)
+        e = f()
+        p.repr_failure_explanation(e, source)
+        assert p.stringio.getvalue().startswith(">   ")
+
+    def test_repr_local(self):
+        p = self.getpresenter("--showlocals") 
+        loc = locals()
+        p.repr_locals(loc) 
+        result = p.stringio.getvalue()
+        for key in loc.keys(): 
+            assert result.find(key) != -1 
+
+    def test_repr_traceback(self):
+        tfile = suptest.makeuniquepyfile(""" 
+            def test_one():
+                assert 42 == 43
+            def f(): 
+                assert 0
+            def test_nested():
+                f()
+        """)
+        sorter = suptest.events_from_cmdline([tfile])
+        p = self.getpresenter()
+
+        failevents = sorter.get(repevent.ItemFinish)
+        assert len(failevents) == 2
+        item = failevents[0].item 
+        py.test.skip("refactor Presenter.repr_failure_*")
+        # errr... here we should
+        # a) prepare an item
+        # b) prepare excinfo
+        # c) prepare some traceback info, with few different ideas,
+        #    like recursion detected etc.
+        # test it...

Deleted: /py/branch/event/py/test2/testing/test_repr.py
==============================================================================
--- /py/branch/event/py/test2/testing/test_repr.py	Thu Feb 14 12:24:20 2008
+++ (empty file)
@@ -1,94 +0,0 @@
-
-import py
-from py.__.test2.representation import Presenter, getmodpath
-from py.__.test2.terminal.out import getout
-from StringIO import StringIO
-import setupdata
-import sys
-
-def test_getmodpath_cases():
-    tmpdir = py.test.ensuretemp("test_getmodpath_cases") 
-    pkgdir = tmpdir.join("pkg") 
-    pkgdir.ensure("__init__.py") 
-    nopkgdir = tmpdir.ensure("nopkg", dir=1) 
-    def checkpkg(names, expected):
-        fcol = setupdata.getexamplecollector(names, tmpdir=pkgdir)
-        assert getmodpath(fcol) == pkgdir.basename + "." + expected 
-    def checknopkg(names, expected):
-        fcol = setupdata.getexamplecollector(names, tmpdir=nopkgdir)
-        assert getmodpath(fcol) == expected 
-
-    for names in (
-        'mod.py test_f1           mod.test_f1', 
-        'mod.py TestA () test_m1  mod.TestA().test_m1', 
-        'mod.py test_g1           mod.test_g1', 
-        'mod.py test_g1 [0]       mod.test_g1[0]', 
-    ):
-        names = names.split()
-        expected = names.pop()
-        yield checkpkg, names, expected 
-        yield checknopkg, names, expected 
-
-def newconfig(*args):
-    tmpdir = py.test2.ensuretemp("newconfig")
-    args = list(args)
-    args.append(tmpdir)
-    return py.test2.config._reparse(args)
-    
-def test_repr_source():
-    source = py.code.Source("""
-    def f(x):
-        pass
-    """).strip()
-    config = newconfig()
-    s = StringIO()
-    out = getout(s)
-    p = Presenter(out, config)
-    p.repr_source(source, "|", 0)
-    lines = s.getvalue().split("\n")
-    assert len(lines) == 3
-    assert lines[0].startswith("|")
-    assert lines[0].find("def f(x)") != -1
-    assert lines[1].find("pass") != -1
-
-def test_repr_failure_explanation():
-    """ We check here if indentation is right
-    """
-    def f():
-        def g():
-            1/0
-        try:
-            g()
-        except:
-            e = py.code.ExceptionInfo()
-        return e
-    config = newconfig()
-    s = StringIO()
-    out = getout(s)
-    p = Presenter(out, config)
-    source = py.code.Source(f)
-    e = f()
-    p.repr_failure_explanation(e, source)
-    assert s.getvalue().startswith(">   ")
-
-def test_repr_local():
-    config = newconfig('--showlocals')
-    s = StringIO()
-    out = getout(s)
-    p = Presenter(out, config)
-    p.repr_locals(locals())
-    for key in locals().keys():
-        assert s.getvalue().find(key) != -1
-
-def XXXtest_repr_traceback_long():
-    py.test.skip("unfinished")
-    config = py.test2.config._reparse([])
-    s = StringIO()
-    out = getout(s)
-    p = Presenter(out, config)
-    # errr... here we should
-    # a) prepare an item
-    # b) prepare excinfo
-    # c) prepare some traceback info, with few different ideas,
-    #    like recursion detected etc.
-    # test it...



More information about the pytest-commit mailing list