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

hpk at codespeak.net hpk at codespeak.net
Thu Feb 14 11:15:10 CET 2008


Author: hpk
Date: Thu Feb 14 11:15:10 2008
New Revision: 51481

Added:
   py/branch/event/py/test2/testing/test_repevent.py
Modified:
   py/branch/event/py/test2/collect.py
   py/branch/event/py/test2/config.py
   py/branch/event/py/test2/repevent.py
   py/branch/event/py/test2/representation.py
   py/branch/event/py/test2/testing/setupdata.py
   py/branch/event/py/test2/testing/suptest.py
   py/branch/event/py/test2/testing/test_repr.py
   py/branch/event/py/test2/testing/test_session.py
Log:
* (intermediate) beginning to get marshallable TestReport, added tests 
* factoring out getmodpath(colitem), added tests
* simplified test example creation



Modified: py/branch/event/py/test2/collect.py
==============================================================================
--- py/branch/event/py/test2/collect.py	(original)
+++ py/branch/event/py/test2/collect.py	Thu Feb 14 11:15:10 2008
@@ -147,29 +147,18 @@
         for name in namelist:
             if name:
                 next = cur.join(name)
-                assert next is not None, (cur, name, namelist)
+                if next is None: 
+                    existingnames = cur.run()
+                    msg = ("Collector %r does not have name %r "
+                           "existing names are: %s" %
+                           (cur, name, existingnames))
+                    raise AssertionError(msg) 
                 cur = next
         return cur
 
     def _keywords(self):
         return [self.name]
 
-    def _getmodpath(self):
-        """ return dotted module path (relative to the containing). """ 
-        inmodule = False 
-        newl = []
-        for x in self.listchain(): 
-            if not inmodule and not isinstance(x, Module): 
-                continue
-            if not inmodule:  
-                inmodule = True
-                continue
-            if newl and x.name[:1] in '([': 
-                newl[-1] += x.name 
-            else: 
-                newl.append(x.name) 
-        return ".".join(newl) 
-
     def _skipbykeyword(self, keywordexpr): 
         """ return True if they given keyword expression means to 
             skip this collector/item. 

Modified: py/branch/event/py/test2/config.py
==============================================================================
--- py/branch/event/py/test2/config.py	(original)
+++ py/branch/event/py/test2/config.py	Thu Feb 14 11:15:10 2008
@@ -237,7 +237,7 @@
             if chain[0].fspath == self.topdir:
                 relpath = "."
             else:
-                raise ValueError("%r not relative to %s" 
+                raise ValueError("%r not relative to topdir %s" 
                          %(chain[0], self.topdir))
         return relpath, tuple([x.name for x in chain[1:]])
 

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 11:15:10 2008
@@ -71,6 +71,12 @@
             assert outcome in ("passed", "failed", "skipped") 
             setattr(self, outcome, True) 
 
+    def dottedpath(self, config):
+        """ return dotted path for underlying test item. """ 
+        from py.__.test2.representation import getmodpath 
+        col = config._getcollector(self.trail) 
+        return getmodpath(col) 
+
     def dumps(self):
         """ marshal all possible attr to a string. """ 
         d = {}

Modified: py/branch/event/py/test2/representation.py
==============================================================================
--- py/branch/event/py/test2/representation.py	(original)
+++ py/branch/event/py/test2/representation.py	Thu Feb 14 11:15:10 2008
@@ -19,6 +19,21 @@
     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

Modified: py/branch/event/py/test2/testing/setupdata.py
==============================================================================
--- py/branch/event/py/test2/testing/setupdata.py	(original)
+++ py/branch/event/py/test2/testing/setupdata.py	Thu Feb 14 11:15:10 2008
@@ -10,19 +10,26 @@
 #        getexamplefile(name)
 #    return datadir
 
-def getexamplefile(basename):
-    datadir = py.test2.ensuretemp("example") 
-    datadir.ensure("__init__.py")
-    path = datadir.join(basename) 
+def getexamplefile(basename, tmpdir=None):
+    if tmpdir is None: 
+        tmpdir = py.test2.ensuretemp("example") 
+        tmpdir.ensure("__init__.py")
+    path = tmpdir.join(basename) 
     if not path.check():
-        path.write(namecontent[basename]) 
+        path.write(py.code.Source(namecontent[basename]))
         print "creating testfile", path
     return path 
 
+def getexamplecollector(names, tmpdir=None): 
+    fn = getexamplefile(names[0], tmpdir=tmpdir)  
+    config = py.test2.config._reparse([fn.dirpath()])
+    col = config._getcollector(fn)
+    return col._getitembynames(names[1:])
+
 namecontent = {
     'syntax_error.py': "this is really not python\n",
 
-    'disabled_module.py': py.code.Source('''
+    'disabled_module.py': '''
         disabled = True
 
         def setup_module(mod):
@@ -37,9 +44,9 @@
                 raise ValueError
             def test_func(self):
                 raise ValueError
-    '''), 
+    ''', 
 
-    'brokenrepr.py': py.code.Source('''
+    'brokenrepr.py': '''
         import py
 
         class BrokenRepr1:
@@ -70,15 +77,21 @@
             def test_implicit_bad_repr2(self):
                 t = BrokenRepr2()
                 assert t.foo == 1
-    '''),
-
-    'failingimport.py': py.code.Source('''
+    ''', 
 
-     import gruetzelmuetzel
+    'failingimport.py': "import gruetzelmuetzel\n", 
 
-    '''),
+    'mod.py': """
+        class TestA:
+            def test_m1(self):
+                pass
+        def test_f1():
+            pass
+        def test_g1():
+            yield lambda x: None, 42
+    """,
 
-    'filetest.py': py.code.Source('''
+    'filetest.py': """
         def test_one(): 
             assert 42 == 43
 
@@ -86,9 +99,9 @@
             def test_method_one(self): 
                 assert 42 == 43 
 
-    '''),
+    """,
 
-    'test_threepass.py': py.code.Source('''
+    'test_threepass.py': """
         def test_one():
             assert 1
 
@@ -97,22 +110,22 @@
 
         def test_three():
             assert 1
-    '''),
+    """,
 
-    'testspecial_importerror.py': py.code.Source('''
+    'testspecial_importerror.py': """
 
         import asdasd
 
-    '''),
+    """,
 
-    'disabled.py': py.code.Source('''
+    'disabled.py': """
         class TestDisabled:
             disabled = True
             def test_method(self): 
                 pass
-    '''),
+    """,
 
-    'funcexamples.py': py.code.Source('''
+    'funcexamples.py': """
         import py
         import time
         def funcpassed(): 
@@ -146,9 +159,9 @@
         def funchang():
             import time
             time.sleep(1000)
-    '''),
+    """,
     
-    'test_generative.py': py.code.Source("""
+    'test_generative.py': """ 
         from __future__ import generators # python2.2!
         def func1(arg, arg2): 
             assert arg == arg2 
@@ -161,13 +174,12 @@
             def test_gen(self): 
                 yield func1, 17, 3*5
                 yield func1, 42, 6*7
-    """), 
+    """, 
 
-    'docexample.txt': py.code.Source("""
+    'docexample.txt': """ 
         Aha!!!!!!
         =========
-
-     """),
+     """,
 
 } 
 

Modified: py/branch/event/py/test2/testing/suptest.py
==============================================================================
--- py/branch/event/py/test2/testing/suptest.py	(original)
+++ py/branch/event/py/test2/testing/suptest.py	Thu Feb 14 11:15:10 2008
@@ -47,6 +47,7 @@
 
 class EventSorter(object):
     def __init__(self, config, session=None):
+        self.config = config
         self.session = session
         self.cls2events = d = {}
         def app(event):
@@ -63,7 +64,7 @@
         passed = []
         skipped = []
         failed = []
-        for ev in self.get(repevent.ItemFinish):
+        for ev in self.get(repevent.ItemTestReport):
             if ev.passed: 
                 passed.append(ev) 
             elif ev.skipped: 

Added: py/branch/event/py/test2/testing/test_repevent.py
==============================================================================
--- (empty file)
+++ py/branch/event/py/test2/testing/test_repevent.py	Thu Feb 14 11:15:10 2008
@@ -0,0 +1,38 @@
+
+from py.__.test2 import repevent 
+import setupdata, suptest
+
+class TestItemTestReport(object):
+    def _makevent(self, names, **kwargs): 
+        fcol = setupdata.getexamplecollector(names)
+        trail = fcol._get_collector_trail()
+        ev = repevent.ItemTestReport(trail, **kwargs) 
+        ev._col = fcol 
+        return ev
+
+    def test_dumps_loads(self):
+        ev = self._makevent(["filetest.py", 'test_one'], outcome="skipped") 
+        ev.whatever = 42
+        class A: pass
+        ev.a = A()
+        assert ev.skipped 
+        s = ev.dumps()
+        ev2 = repevent.ItemTestReport.loads(s) 
+        assert ev2.skipped 
+        assert ev2.trail == ev.trail 
+        assert ev2.dottedpath(ev._col._config).endswith("filetest.test_one") 
+        assert ev2.whatever == 42
+        assert not hasattr(ev2, 'a')
+    
+    def test_ItemTestReport(self):
+        ev = self._makevent(["filetest.py", 'test_one'], outcome="passed") 
+        assert ev.dottedpath(ev._col._config).endswith("filetest.test_one") 
+
+    def test_failing(self):
+        sorter = suptest.events_run_example("filetest.py")
+        reports = sorter.get(repevent.ItemTestReport)
+        ev = reports[0] 
+        assert ev.failed 
+        assert ev.exconly.find("AssertionError") != -1
+        
+

Modified: 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_repr.py	Thu Feb 14 11:15:10 2008
@@ -1,10 +1,34 @@
 
 import py
-from py.__.test2.representation import Presenter
+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)

Modified: py/branch/event/py/test2/testing/test_session.py
==============================================================================
--- py/branch/event/py/test2/testing/test_session.py	(original)
+++ py/branch/event/py/test2/testing/test_session.py	Thu Feb 14 11:15:10 2008
@@ -12,7 +12,7 @@
                 '-s', '-k', keyword)
             passed, skipped, failed = sorter.listoutcomes()
             assert len(failed) == 1
-            assert failed[0].item.name == name 
+            assert failed[0].dottedpath(sorter.config).endswith(name) 
             des = sorter.get(repevent.DeselectedTest)
             assert len(des) == 1
 
@@ -41,7 +41,7 @@
             print "keyword", repr(keyword)
             passed, skipped, failed = sorter.listoutcomes()
             assert len(passed) == 1
-            assert passed[0].item.name == 'test_2'
+            assert passed[0].dottedpath(sorter.config).endswith('test_2')
             assert not skipped 
             deslist = sorter.get(repevent.DeselectedTest)
             assert len(deslist) == 1
@@ -105,20 +105,19 @@
             import py
             class Function(py.test2.collect.Function): 
                 def startcapture(self): 
-                    self._mycapture = None
+                    self._mycapture = True
                     
                 def finishcapture(self): 
-                    self._testmycapture = None
+                    self._testmycapture = True
         """))
         sorter = suptest.events_from_cmdline([tfile.dirpath()])
         passed, skipped, failed = sorter.listoutcomes()
         assert len(passed) == 1
         assert len(failed) == 1
 
-        assert hasattr(passed[0].item, '_mycapture')
-        assert hasattr(passed[0].item, '_testmycapture')
-        assert hasattr(failed[0].item, '_mycapture')
-        assert hasattr(failed[0].item, '_testmycapture')
+        for ev in sorter.get(repevent.ItemFinish): 
+            assert ev.item._mycapture 
+            assert ev.item._testmycapture 
 
     def test_raises_output(self): 
         p = suptest.makeuniquepyfile('''
@@ -129,7 +128,7 @@
         sorter = suptest.events_from_cmdline([p])
         passed, skipped, failed = sorter.listoutcomes()
         assert len(failed) == 1
-        out = failed[0].excinfo.exconly()
+        out = failed[0].exconly
         if not out.find("DID NOT RAISE") != -1: 
             print out
             py.test2.fail("incorrect raises() output") 


More information about the py-svn mailing list