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

hpk at codespeak.net hpk at codespeak.net
Wed Aug 6 23:02:52 CEST 2008


Author: hpk
Date: Wed Aug  6 23:02:49 2008
New Revision: 57044

Modified:
   py/branch/event/py/test2/collect.py
   py/branch/event/py/test2/pycollect.py
   py/branch/event/py/test2/testing/acceptance_test.py
   py/branch/event/py/test2/testing/test_doctest.py
Log:
integrate doctests running into new reporting architecture 
(and port doctest changes from trunk rev 56285)


Modified: py/branch/event/py/test2/collect.py
==============================================================================
--- py/branch/event/py/test2/collect.py	(original)
+++ py/branch/event/py/test2/collect.py	Wed Aug  6 23:02:49 2008
@@ -228,6 +228,8 @@
                 repr.addsection("Captured std%s" % secname, content.rstrip())
         return repr 
 
+    getfailurerepr = _getfailurerepr_py
+
     shortfailurerepr = "F"
 
 class Collector(Node):

Modified: py/branch/event/py/test2/pycollect.py
==============================================================================
--- py/branch/event/py/test2/pycollect.py	(original)
+++ py/branch/event/py/test2/pycollect.py	Wed Aug  6 23:02:49 2008
@@ -267,45 +267,52 @@
         """ execute the given test function. """
         self.obj(*self._args)
 
-class DoctestFile(PyCollectorMixin, FSCollector): 
+class DoctestFile(FSCollector): 
     def listdir(self):
         return [self.fspath.basename]
 
     def join(self, name):
         if name == self.fspath.basename: 
-            item = DoctestText(self.fspath.basename, parent=self)
-            item._content = self.fspath.read()
-            return item
+            return DoctestFileContent(name, self)
 
-class DoctestText(Item):
-    #XXX port changes from dist/trunk 
-    def _setcontent(self, content):
-        self._content = content 
+from py.__.code.excinfo import Repr, ReprFileLocation
 
-    #def buildname2items(self):
-    #    parser = py.compat.doctest.DoctestParser()
-    #    l = parser.get_examples(self._content)
-    #    d = {}
-    #    globs = {}
-    #    locs
-    #    for i, example in py.builtin.enumerate(l):
-    #        ex = ExampleItem(example)
-    #        d[str(i)] = ex
-
-    def run(self):
-        mod = py.std.types.ModuleType(self.name) 
-        #for line in s.split('\n'): 
-        #    if line.startswith(prefix): 
-        #        exec py.code.Source(line[len(prefix):]).compile() in mod.__dict__ 
-        #        line = ""
-        #    else: 
-        #        l.append(line)
-        self.execute(mod, self._content) 
-       
-    def execute(self, mod, docstring):
-        mod.__doc__ = docstring 
-        failed, tot = py.compat.doctest.testmod(mod, verbose=1)
-        if failed: 
-            py.test2.fail("doctest %s: %s failed out of %s" %(
-                         self.fspath, failed, tot))
+class ReprFailDoctest(Repr):
+    def __init__(self, reprlocation, lines):
+        self.reprlocation = reprlocation
+        self.lines = lines
+    def toterminal(self, tw):
+        for line in self.lines:
+            tw.line(line)
+        self.reprlocation.toterminal(tw)
+             
+class DoctestFileContent(Item):
+    def getfailurerepr(self, excinfo, outerr):
+        if excinfo.errisinstance(py.compat.doctest.DocTestFailure):
+            doctestfailure = excinfo.value
+            example = doctestfailure.example
+            test = doctestfailure.test
+            filename = test.filename 
+            lineno = example.lineno + 1
+            message = excinfo.type.__name__
+            reprlocation = ReprFileLocation(filename, lineno, message)
+            checker = py.compat.doctest.OutputChecker() 
+            REPORT_UDIFF = py.compat.doctest.REPORT_UDIFF
+            filelines = py.path.local(filename).readlines(cr=0)
+            i = max(0, lineno - 10)
+            lines = []
+            for line in filelines[i:lineno]:
+                lines.append("%03d %s" % (i+1, line))
+                i += 1
+            lines += checker.output_difference(example, 
+                    doctestfailure.got, REPORT_UDIFF).split("\n")
+            return ReprFailDoctest(reprlocation, lines)
+        #elif excinfo.errisinstance(py.compat.doctest.UnexpectedException):
+        else: 
+            return super(DoctestFileContent, self).getfailurerepr(excinfo, outerr)
+            
+    def execute(self):
+        failed, tot = py.compat.doctest.testfile(
+            str(self.fspath), module_relative=False, 
+            raise_on_error=True, verbose=0)
 

Modified: py/branch/event/py/test2/testing/acceptance_test.py
==============================================================================
--- py/branch/event/py/test2/testing/acceptance_test.py	(original)
+++ py/branch/event/py/test2/testing/acceptance_test.py	Wed Aug  6 23:02:49 2008
@@ -25,9 +25,13 @@
         return Result(ret, out, err)
 
     def makepyfile(self, **kwargs):
+        return self._makefile('.py', **kwargs)
+    def maketxtfile(self, **kwargs):
+        return self._makefile('.txt', **kwargs)
+    def _makefile(self, ext, **kwargs):
         ret = None
         for name, value in kwargs.iteritems():
-            p = py.path.local(name).new(ext=".py")
+            p = py.path.local(name).new(ext=ext)
             source = py.code.Source(value)
             p.write(str(py.code.Source(value)).lstrip())
             if ret is None:
@@ -231,6 +235,23 @@
             "x* = 3",
             "y* = 'xxxxxx*"
         ])
+
+    def test_doctest_simple_failing(self):
+        p = self.maketxtfile(doc="""
+            >>> i = 0
+            >>> i + 1
+            2
+        """)
+        result = self.runpytest(p)
+        assert_lines_contain_lines(result.outlines, [
+            '001 >>> i = 0',
+            '002 >>> i + 1',
+            'Expected:',
+            "    2",
+            "Got:",
+            "    1",
+            "*doc.txt:2: DocTestFailure"
+        ])
         
     def test_looponfailing_looping(self):
         py.test.skip("thought needed to nicely test --looponfailing")

Modified: py/branch/event/py/test2/testing/test_doctest.py
==============================================================================
--- py/branch/event/py/test2/testing/test_doctest.py	(original)
+++ py/branch/event/py/test2/testing/test_doctest.py	Wed Aug  6 23:02:49 2008
@@ -1,24 +1,31 @@
 
 import py
-from py.__.test2.pycollect import DoctestText
-from py.__.test2.outcome import Failed
+from py.__.test2.outcome import Failed 
+
+def setup_module(mod):
+    mod.tmp = py.test.ensuretemp(__name__) 
 
 def test_simple_docteststring():
-    testitem = DoctestText(name="dummy", parent=None, config=42)
-    testitem._setcontent("""
-    >>> i = 0
-    >>> i + 1
-    1
-    """)
-    res = testitem.run()
+    p = tmp.join("test_simple_docteststring") 
+    p.write(py.code.Source("""
+        >>> i = 0
+        >>> i + 1
+        1
+    """))
+    testitem = py.test.collect.DoctestFile(p).join(p.basename) 
+    res = testitem.execute()
     assert res is None
     
-def test_simple_docteststring_failing():
-    testitem = DoctestText(name="dummy2", parent=None, config=42)
-    testitem._setcontent("""
-    >>> i = 0
-    >>> i + 1
-    2
-    """)
-    py.test2.raises(Failed, "testitem.run()")
-   
+
+def test_doctest_unexpected_exception():
+    py.test.skip("implement nice doctest repr for unexpected exceptions")
+    p = tmp.join("test_doctest_unexpected_exception")
+    p.write(py.code.Source("""
+        >>> i = 0
+        >>> x
+        2
+    """))
+    testitem = py.test.collect.DoctestFile(p).join(p.basename)
+    excinfo = py.test.raises(Failed, "testitem.execute()")
+    repr = testitem.getfailurerepr(excinfo, ("", ""))
+    assert repr.reprlocation 



More information about the pytest-commit mailing list