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

hpk at codespeak.net hpk at codespeak.net
Tue Feb 12 18:06:07 CET 2008


Author: hpk
Date: Tue Feb 12 18:06:06 2008
New Revision: 51416

Added:
   py/branch/event/py/test2/genitem.py
Modified:
   py/branch/event/py/test2/collect.py
   py/branch/event/py/test2/rsession/testing/basetest.py
   py/branch/event/py/test2/rsession/testing/test_masterslave.py
   py/branch/event/py/test2/rsession/testing/test_rsession.py
   py/branch/event/py/test2/rsession/testing/test_slave.py
   py/branch/event/py/test2/session.py
   py/branch/event/py/test2/testing/setupdata.py
   py/branch/event/py/test2/testing/test_collect.py
   py/branch/event/py/test2/testing/test_doctest.py
   py/branch/event/py/test2/testing/test_executor.py
   py/branch/event/py/test2/testing/test_remote.py
   py/branch/event/py/test2/testing/test_session.py
Log:
* get rid of _tryiter usages, port tests to new itemgen
* factor out 'genitem()' generator 
* refactor tests 



Modified: py/branch/event/py/test2/collect.py
==============================================================================
--- py/branch/event/py/test2/collect.py	(original)
+++ py/branch/event/py/test2/collect.py	Tue Feb 12 18:06:06 2008
@@ -26,6 +26,8 @@
 from __future__ import generators 
 import py
 
+sysex = (KeyboardInterrupt, SystemExit, GeneratorExit)
+
 def configproperty(name):
     def fget(self):
         #print "retrieving %r property from %s" %(name, self.fspath)
@@ -201,26 +203,6 @@
                 return True
         return False
 
-    def _tryiter(self, yieldtype=None):
-        """ yield stop item instances from flattening the collector. 
-            XXX deprecated: this way of iteration is not safe in all
-            cases. 
-        """ 
-        if yieldtype is None: 
-            yieldtype = py.test2.collect.Item 
-        if isinstance(self, yieldtype):
-            yield self
-        else:
-            if not isinstance(self, py.test2.collect.Item):
-                try:
-                    for x in self.run(): 
-                        for y in self.join(x)._tryiter(yieldtype):
-                            yield y
-                except KeyboardInterrupt:
-                    raise
-                except:
-                    pass
-
     def _getsortvalue(self): 
         return self.name 
 
@@ -257,6 +239,9 @@
         if path.check(dir=1, dotfile=0):
             return path.basename not in ('CVS', '_darcs', '{arch}')
 
+    def list(self):
+        return [self.join(x) for x in self.run()]
+
     def run(self):
         files = []
         dirs = []
@@ -428,9 +413,6 @@
             return py.path.local(file), lineno
         except IOError:
             pass
-        # fall back...
-        for x in self._tryiter((py.test2.collect.Generator, py.test2.collect.Item)):
-            return x._getsortvalue()
 
 class Instance(PyCollectorMixin, Collector): 
     def _getobj(self): 
@@ -455,7 +437,7 @@
 
     def setup(self): 
         """ perform setup for this test function. """
-        if getattr(self.obj, 'im_self', None): 
+        if hasattr(self.obj, 'im_self'):
             name = 'setup_method' 
         else: 
             name = 'setup_function' 
@@ -466,7 +448,7 @@
 
     def teardown(self): 
         """ perform teardown for this test function. """
-        if getattr(self.obj, 'im_self', None): 
+        if hasattr(self.obj, 'im_self'):
             name = 'teardown_method' 
         else: 
             name = 'teardown_function' 
@@ -511,3 +493,4 @@
             item = DoctestText(self.fspath.basename, parent=self)
             item._content = self.fspath.read()
             return item
+

Added: py/branch/event/py/test2/genitem.py
==============================================================================
--- (empty file)
+++ py/branch/event/py/test2/genitem.py	Tue Feb 12 18:06:06 2008
@@ -0,0 +1,30 @@
+
+import py
+from py.__.test2 import repevent
+sysex = (KeyboardInterrupt, SystemExit)
+
+def genitems(config, colitems, keywordexpr=None, 
+             stopitems=(py.test2.collect.Item,)):
+    """ yield Items from iterating over the given colitems. """
+    hub = config.hub
+    while colitems: 
+        next = colitems.pop(0)
+        if isinstance(next, stopitems):
+            if next._skipbykeyword(keywordexpr):
+                hub.notify(repevent.DeselectedTest(next, keywordexpr))
+                if config.option.keyword_oneshot:
+                    keywordexpr = None
+            else:
+                yield next 
+        else:
+            hub.notify(repevent.CollectionStart(next))
+            excinfo = None
+            try:
+                cols = [next.join(x) for x in next.run()]
+                for x in genitems(config, cols, keywordexpr):
+                    yield x
+            except sysex: 
+                raise
+            except:
+                excinfo = py.code.ExceptionInfo()
+            hub.notify(repevent.CollectionFinish(next, excinfo))

Modified: py/branch/event/py/test2/rsession/testing/basetest.py
==============================================================================
--- py/branch/event/py/test2/rsession/testing/basetest.py	(original)
+++ py/branch/event/py/test2/rsession/testing/basetest.py	Tue Feb 12 18:06:06 2008
@@ -3,55 +3,19 @@
 """
 
 import py
-
-def func_source():
-    import py
-    import time
-    def funcpassed(): 
-        pass
-
-    def funcfailed():
-        raise AssertionError("hello world")
-
-    def funcskipped():
-        py.test2.skip("skipped")
-
-    def funcprint():
-        print "samfing"
-
-    def funcprintfail():
-        print "samfing elz"
-        asddsa
-
-    def funcoptioncustom():
-        assert py.test2.config.getvalue("custom")
-
-    def funchang():
-        import time
-        time.sleep(1000)
+from py.__.test2.testing.setupdata import getexamplefile 
 
 class BasicRsessionTest(object):
     def setup_class(cls):
-        tmpdir = py.test2.ensuretemp(cls.__name__) 
-        source = py.code.Source(func_source)[1:].deindent()
-        testonepath = tmpdir.ensure("test_one.py")
-        testonepath.write(source)
-        cls.config = py.test2.config._reparse([tmpdir])
-        cls.collector_test_one = cls.config._getcollector(testonepath)
-        cls.doctest = tmpdir.ensure("xxx.txt").write(py.code.Source("""
-        Aha!!!!!!
-        =========
-
-        """))
-
-    def getexample(self, name):
+        path = getexamplefile("funcexamples.py")
+        cls.config = py.test2.config._reparse([path.dirpath()])
+        cls.modulecol = cls.config._getcollector(path)
+        
+    def getfunc(self, name):
         funcname = "func" + name
-        col = self.collector_test_one.join(funcname)
+        col = self.modulecol.join(funcname) 
         assert col is not None, funcname
         return col
 
     def getdocexample(self):
-        return self.doctest
-
-    def getmod(self):
-        return self.collector_test_one
+        return getexamplefile("docexample.txt")

Modified: py/branch/event/py/test2/rsession/testing/test_masterslave.py
==============================================================================
--- py/branch/event/py/test2/rsession/testing/test_masterslave.py	(original)
+++ py/branch/event/py/test2/rsession/testing/test_masterslave.py	Tue Feb 12 18:06:06 2008
@@ -33,7 +33,7 @@
         assert not node.channel.isclosed()
 
         queue = self.makereportqueue()
-        node.send(self.getexample("passed"))
+        node.send(self.getfunc("passed"))
         event = queue.get(timeout=2.0)
         assert event.passed 
         assert not node.pending
@@ -46,7 +46,7 @@
 
         queue = self.makereportqueue()
         for outcome in "passed failed skipped".split():
-            node.send(self.getexample(outcome))
+            node.send(self.getfunc(outcome))
             event = queue.get(timeout=2.0)
             assert getattr(event, outcome) 
         assert not node.pending

Modified: py/branch/event/py/test2/rsession/testing/test_rsession.py
==============================================================================
--- py/branch/event/py/test2/rsession/testing/test_rsession.py	(original)
+++ py/branch/event/py/test2/rsession/testing/test_rsession.py	Tue Feb 12 18:06:06 2008
@@ -94,10 +94,10 @@
         # actually run some tests
         for host in hm.hosts: 
             node = host.node
-            node.send(self.getexample("passed"))
-            node.send(self.getexample("failed")) 
-            node.send(self.getexample("skipped"))
-            node.send(self.getexample("print"))
+            node.send(self.getfunc("passed"))
+            node.send(self.getfunc("failed")) 
+            node.send(self.getfunc("skipped"))
+            node.send(self.getfunc("print"))
 
         num_hosts = len(hm.hosts) 
         events = []

Modified: py/branch/event/py/test2/rsession/testing/test_slave.py
==============================================================================
--- py/branch/event/py/test2/rsession/testing/test_slave.py	(original)
+++ py/branch/event/py/test2/rsession/testing/test_slave.py	Tue Feb 12 18:06:06 2008
@@ -22,7 +22,7 @@
 
     def test_slave_run_passing(self):
         node = self.gettestnode()
-        item = self.getexample("passed")
+        item = self.getfunc("passed")
         outcome = node.execute(item._get_collector_trail())
         assert outcome.passed 
         assert not outcome.setupfailure 
@@ -34,7 +34,7 @@
 
     def test_slave_run_failing(self):
         node = self.gettestnode()
-        item = self.getexample("failed") 
+        item = self.getfunc("failed") 
         outcome = node.execute(item._get_collector_trail())
         assert not outcome.passed 
         assert not outcome.setupfailure 
@@ -49,7 +49,7 @@
     
     def test_slave_run_skipping(self):
         node = self.gettestnode()
-        item = self.getexample("skipped")
+        item = self.getfunc("skipped")
         outcome = node.execute(item._get_collector_trail())
         assert not outcome.passed
         assert outcome.skipped
@@ -61,7 +61,7 @@
 
     def test_slave_run_failing_wrapped(self):
         node = self.gettestnode()
-        item = self.getexample("failed") 
+        item = self.getfunc("failed") 
         repr_outcome = node.run(item._get_collector_trail()) 
         outcome = ReprOutcome(repr_outcome)  
         assert not outcome.passed 

Modified: py/branch/event/py/test2/session.py
==============================================================================
--- py/branch/event/py/test2/session.py	(original)
+++ py/branch/event/py/test2/session.py	Tue Feb 12 18:06:06 2008
@@ -6,12 +6,11 @@
 """
 
 import py
+from py.__.test2.genitem import genitems 
 from py.__.test2 import repevent
 from py.__.test2.outcome import ReprOutcome
 from py.__.test2.executor import RunExecutor, BoxExecutor
 
-GeneratorExit = py.builtin.GeneratorExit 
-
 class Session(object): 
     """ 
         Session drives the collection and running of tests
@@ -41,34 +40,9 @@
     def collect(self): 
         colitems = self.config.getcolitems()
         keyword = self.config.option.keyword
-        for x in self.genitems(colitems, keyword):
+        for x in genitems(self.config, colitems, keyword):
             yield x
 
-    def genitems(self, colitems, keywordexpr=None):
-        hub = self.config.hub
-        stopitems = py.test2.collect.Item 
-        while colitems: 
-            next = colitems.pop(0)
-            if isinstance(next, stopitems):
-                if next._skipbykeyword(keywordexpr):
-                    hub.notify(repevent.DeselectedTest(next, keywordexpr))
-                    if self.config.option.keyword_oneshot:
-                        keywordexpr = None
-                else:
-                    yield next 
-            else:
-                hub.notify(repevent.CollectionStart(next))
-                excinfo = None
-                try:
-                    cols = [next.join(x) for x in next.run()]
-                    for x in self.genitems(cols, keywordexpr):
-                        yield x
-                except (KeyboardInterrupt, SystemExit, GeneratorExit):
-                    raise
-                except:
-                    excinfo = py.code.ExceptionInfo()
-                hub.notify(repevent.CollectionFinish(next, excinfo))
-
     def setup(self):
         """ setup any neccessary resources ahead of the test run. """
         if not self.config.option.nomagic:

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	Tue Feb 12 18:06:06 2008
@@ -1,21 +1,26 @@
 import py
 
-def setup_module(mod):
-    mod.datadir = setupdatadir()
-    mod.tmpdir = py.test2.ensuretemp(mod.__name__) 
-
-def setupdatadir():
-    datadir = py.test2.ensuretemp("datadir")
-    names = [x.basename for x in datadir.listdir()]
-    for name, content in namecontent:
-        if name not in names:
-            datadir.join(name).write(content)
-    return datadir
+#def setup_module(mod):
+#    mod.datadir = setupdatadir()
+#    mod.tmpdir = py.test2.ensuretemp(mod.__name__) 
+
+#def setupdatadir():
+#    datadir = py.test2.ensuretemp("datadir")
+#    for name in namecontent:
+#        getexamplefile(name)
+#    return datadir
+
+def getexamplefile(basename):
+    datadir = py.test2.ensuretemp("datadir") 
+    path = datadir.join(basename) 
+    if not path.check():
+        path.write(namecontent[basename]) 
+    return path 
 
-namecontent = [
-('syntax_error.py', "this is really not python\n"),
+namecontent = {
+    'syntax_error.py': "this is really not python\n",
 
-('disabled_module.py', py.code.Source('''
+    'disabled_module.py': py.code.Source('''
         disabled = True
 
         def setup_module(mod):
@@ -30,49 +35,48 @@
                 raise ValueError
             def test_func(self):
                 raise ValueError
-''')),
+    '''), 
 
-('brokenrepr.py', py.code.Source('''
+    'brokenrepr.py': py.code.Source('''
+        import py
 
-    import py
+        class BrokenRepr1:
+            """A broken class with lots of broken methods. Let's try to make the test framework 
+            immune to these."""
+            foo=0
+            def __repr__(self):
+                raise Exception("Ha Ha fooled you, I'm a broken repr().")
+
+        class BrokenRepr2:
+            """A broken class with lots of broken methods. Let's try to make the test framework 
+            immune to these."""
+            foo=0
+            def __repr__(self):
+                raise "Ha Ha fooled you, I'm a broken repr()."
 
-    class BrokenRepr1:
-        """A broken class with lots of broken methods. Let's try to make the test framework 
-        immune to these."""
-        foo=0
-        def __repr__(self):
-            raise Exception("Ha Ha fooled you, I'm a broken repr().")
-
-    class BrokenRepr2:
-        """A broken class with lots of broken methods. Let's try to make the test framework 
-        immune to these."""
-        foo=0
-        def __repr__(self):
-            raise "Ha Ha fooled you, I'm a broken repr()."
-
-        
-    class TestBrokenClass:
-
-        def test_explicit_bad_repr(self):
-            t = BrokenRepr1()
-            py.test2.raises(Exception, 'repr(t)')
             
-        def test_implicit_bad_repr1(self):
-            t = BrokenRepr1()
-            assert t.foo == 1
-
-        def test_implicit_bad_repr2(self):
-            t = BrokenRepr2()
-            assert t.foo == 1
-    ''')),
+        class TestBrokenClass:
 
-    ('failingimport.py', py.code.Source('''
+            def test_explicit_bad_repr(self):
+                t = BrokenRepr1()
+                py.test2.raises(Exception, 'repr(t)')
+                
+            def test_implicit_bad_repr1(self):
+                t = BrokenRepr1()
+                assert t.foo == 1
+
+            def test_implicit_bad_repr2(self):
+                t = BrokenRepr2()
+                assert t.foo == 1
+    '''),
+
+    'failingimport.py': py.code.Source('''
 
      import gruetzelmuetzel
 
-    ''')),
+    '''),
 
-    ('filetest.py', py.code.Source('''
+    'filetest.py': py.code.Source('''
         def test_one(): 
             assert 42 == 43
 
@@ -80,8 +84,9 @@
             def test_method_one(self): 
                 assert 42 == 43 
 
-    ''')),
-    ('testmore.py', py.code.Source('''
+    '''),
+
+    'testmore.py': py.code.Source('''
         def test_one():
             assert 1
 
@@ -90,21 +95,67 @@
 
         def test_three():
             assert 1
-    ''')),
+    '''),
 
-    ('testspecial_importerror.py', py.code.Source('''
+    'testspecial_importerror.py': py.code.Source('''
 
         import asdasd
 
-    ''')),
+    '''),
 
-    ('disabled.py', py.code.Source('''
+    'disabled.py': py.code.Source('''
         class TestDisabled:
             disabled = True
             def test_method(self): 
                 pass
-    ''')),
-]    
-   
+    '''),
+
+    'funcexamples.py': py.code.Source('''
+        import py
+        import time
+        def funcpassed(): 
+            pass
+
+        def funcfailed():
+            raise AssertionError("hello world")
+
+        def funcskipped():
+            py.test2.skip("skipped")
+
+        def funcprint():
+            print "samfing"
+
+        def funcprintfail():
+            print "samfing elz"
+            asddsa
+
+        def funcoptioncustom():
+            assert py.test2.config.getvalue("custom")
+
+        def funchang():
+            import time
+            time.sleep(1000)
+    '''),
+    
+    'test_generative.py': py.code.Source("""
+        from __future__ import generators # python2.2!
+        def func1(arg, arg2): 
+            assert arg == arg2 
+
+        def test_gen(): 
+            yield func1, 17, 3*5
+            yield func1, 42, 6*7
+
+        class TestGenMethods: 
+            def test_gen(self): 
+                yield func1, 17, 3*5
+                yield func1, 42, 6*7
+    """), 
+
+    'docexample.txt': py.code.Source("""
+        Aha!!!!!!
+        =========
+
+     """),
 
- 
+} 

Modified: py/branch/event/py/test2/testing/test_collect.py
==============================================================================
--- py/branch/event/py/test2/testing/test_collect.py	(original)
+++ py/branch/event/py/test2/testing/test_collect.py	Tue Feb 12 18:06:06 2008
@@ -1,11 +1,11 @@
 from __future__ import generators
 import py
-from setupdata import setupdatadir
-from py.__.test2.outcome import Skipped, Failed, Passed, Outcome
-from py.__.test2.terminal.out import getout
-from py.__.test2.repevent import ItemFinish
+from py.__.test2 import outcome 
 from test_session import getevents_runmain
 from py.__.test2 import repevent
+from py.__.test2.genitem import genitems
+from py.__.test2.doctest import DoctestText
+from setupdata import getexamplefile 
 
 def getpassed(session):
     hub = session.config.hub
@@ -14,25 +14,33 @@
     try:
         session.main()
         print all
-        passed = [i.passed for i in all if isinstance(i, ItemFinish)]
+        passed = [i.passed for i in all if isinstance(i, repevent.ItemFinish)]
         return passed
     finally:
         hub.pop()
 
+def eventappender(config):
+    l = []
+    def app(ev):
+        print ev
+        l.append(ev)
+    config.hub.append(app)
+    return l 
+
 def setup_module(mod):
-    mod.datadir = setupdatadir()
-    mod.tmpdir = py.test2.ensuretemp('test_collect') 
+    mod.tmpdir = py.test2.ensuretemp(mod.__name__) 
 
 def test_failing_import_execfile():
-    dest = datadir / 'failingimport.py'
+    dest = getexamplefile('failingimport.py')
     col = py.test2.collect.Module(dest) 
     py.test2.raises(ImportError, col.run)
     py.test2.raises(ImportError, col.run)
 
 def test_collect_listnames_and_back():
-    col1 = py.test2.collect.Directory(datadir.dirpath())
-    col2 = col1.join(datadir.basename) 
-    col3 = col2.join('filetest.py')
+    path = getexamplefile("filetest.py")
+    col1 = py.test2.collect.Directory(path.dirpath().dirpath())
+    col2 = col1.join(path.dirpath().basename) 
+    col3 = col2.join(path.basename) 
     l = col3.listnames()
     assert len(l) == 3
     x = col1._getitembynames(l[1:])
@@ -43,7 +51,7 @@
     assert len(l2) == 3
 
 def test_finds_tests(): 
-    fn = datadir / 'filetest.py'
+    fn = getexamplefile('filetest.py') 
     col = py.test2.collect.Module(fn) 
     l = col.run() 
     assert len(l) == 2 
@@ -56,11 +64,10 @@
     tmp.ensure('found_test.py')
 
     colitem = py.test2.collect.Directory(tmp) 
-    items = list(colitem._tryiter(py.test2.collect.Module))
+    items = colitem.list()
     assert len(items) == 2
-    items = [item.name for item in items]
-    assert 'test_found.py' in items
-    assert 'found_test.py' in items
+    assert items[1].name == 'test_found.py'
+    assert items[0].name == 'found_test.py'
 
 def test_ignored_certain_directories(): 
     tmp = py.test2.ensuretemp("ignore_certain_directories")
@@ -73,16 +80,17 @@
     tmp.ensure('test_found.py')
 
     colitem = py.test2.collect.Directory(tmp) 
-    items = list(colitem._tryiter(py.test2.collect.Module))
+    items = colitem.run()
     assert len(items) == 2
-    for item in items: 
-        assert item.name == 'test_found.py' 
+    assert 'normal' in items 
+    assert 'test_found.py' in items 
 
 def test_failing_import_directory():
     class MyDirectory(py.test2.collect.Directory):
         def filefilter(self, p):
             return p.check(fnmatch='testspecial*.py')
-    mydir = MyDirectory(datadir)
+    filetest = getexamplefile("testspecial_importerror.py")
+    mydir = MyDirectory(filetest.dirpath())
     l = mydir.run() 
     assert len(l) == 1
     item = mydir.join(l[0])
@@ -90,19 +98,17 @@
     py.test2.raises(ImportError, item.run)
 
 def test_module_file_not_found():
-    fn = datadir.join('nada','no')
+    fn = tmpdir.join('nada','no')
     col = py.test2.collect.Module(fn) 
     py.test2.raises(py.error.ENOENT, col.run) 
 
 def test_syntax_error_in_module():
-    p = py.test2.ensuretemp("syntaxerror1").join('syntax_error.py')
-    p.write("\nthis is really not python\n")
-    modpath = datadir.join('syntax_error.py') 
+    modpath = getexamplefile("syntax_error.py")
     col = py.test2.collect.Module(modpath) 
     py.test2.raises(SyntaxError, col.run)
 
 def test_disabled_class():
-    col = py.test2.collect.Module(datadir.join('disabled.py'))
+    col = py.test2.collect.Module(getexamplefile('disabled.py'))
     l = col.run() 
     assert len(l) == 1
     colitem = col.join(l[0])
@@ -110,44 +116,13 @@
     assert not colitem.run() 
 
 def test_disabled_module():
-    col = py.test2.collect.Module(datadir.join('disabled_module.py'))
+    p = getexamplefile("disabled_module.py")
+    col = py.test2.collect.Module(p) 
     l = col.run() 
     assert len(l) == 0
 
-class Testsomeclass:
-    disabled = True
-    def test_something():
-        raise ValueError
-
-
-#class TestWithCustomItem:
-#    class Item(py.test2.collect.Item):
-#        flag = []
-#        def execute(self, target, *args):
-#            self.flag.append(42)
-#            target(*args)
-#
-#    def test_hello(self):
-#        assert self.Item.flag == [42]
-#
-
 def test_generative_simple(): 
-    o = tmpdir.ensure('generativetest', dir=1)
-    tfile = o.join('test_generative.py')
-    tfile.write(py.code.Source("""
-        from __future__ import generators # python2.2!
-        def func1(arg, arg2): 
-            assert arg == arg2 
-
-        def test_gen(): 
-            yield func1, 17, 3*5
-            yield func1, 42, 6*7
-
-        class TestGenMethods: 
-            def test_gen(self): 
-                yield func1, 17, 3*5
-                yield func1, 42, 6*7
-    """))
+    tfile = getexamplefile('test_generative.py')
     col = py.test2.collect.Module(tfile) 
     l = col.run() 
     assert len(l) == 2 
@@ -178,8 +153,9 @@
     assert isinstance(l2[1], py.test2.collect.Function)
     assert l2[0].name == '[0]'
     assert l2[1].name == '[1]'
-   
-def test_custom_python_collection_from_conftest():
+
+
+def setup_customconfigtest(tmpdir):
     o = tmpdir.ensure('customconfigtest', dir=1)
     o.ensure('conftest.py').write("""if 1:
         import py
@@ -207,31 +183,9 @@
             def check_method(self):
                 assert 23 == 23
         """)
+    return checkfile 
 
-    for x in (o, checkfile, checkfile.dirpath()): 
-        config = py.test2.config._reparse([x])
-        #print "checking that %s returns custom items" % (x,) 
-        col = config._getcollector(x)
-        assert len(list(col._tryiter(py.test2.collect.Item))) == 2 
-        #assert items[1].__class__.__name__ == 'MyFunction'
-
-    # test that running a session works from the directories
-    old = o.chdir() 
-    try: 
-        config = py.test2.config._reparse([]) 
-        session = config._getsessionclass()(config)
-        l = getpassed(session)
-        assert len(l) == 2
-    finally: 
-        old.chdir() 
-
-    # test that running the file directly works 
-    config = py.test2.config._reparse([str(checkfile)]) 
-    session = config._getsessionclass()(config)
-    l = getpassed(session) 
-    assert len(l) == 2
-
-def test_custom_NONpython_collection_from_conftest():
+def setup_non_python_dir(tmpdir): 
     o = tmpdir.ensure('customconfigtest_nonpython', dir=1)
     o.ensure('conftest.py').write("""if 1:
         import py
@@ -250,30 +204,9 @@
                     return CustomItem(p, parent=self)
         """)
     checkfile = o.ensure('somedir', 'moredir', 'check_something.txt')
+    return checkfile 
 
-    for x in (o, checkfile, checkfile.dirpath()): 
-        print "checking that %s returns custom items" % (x,) 
-        config = py.test2.config._reparse([x])
-        col = config._getcollector(x)
-        assert len(list(col._tryiter(py.test2.collect.Item))) == 1
-        #assert items[1].__class__.__name__ == 'MyFunction'
-
-    # test that running a session works from the directories
-    old = o.chdir() 
-    try: 
-        config = py.test2.config._reparse([]) 
-        session = config._getsessionclass()(config)
-        l = getpassed(session) 
-        assert len(l) == 1
-    finally: 
-        old.chdir() 
-
-    # test that running the file directly works 
-    config = py.test2.config._reparse([str(checkfile)]) 
-    session = config._getsessionclass()(config)
-    l = getpassed(session) 
-    assert len(l) == 1
-
+    
 def test_order_of_execution_generator_same_codeline():
     o = tmpdir.ensure('genorder1', dir=1)
     o.join("test_order1.py").write(py.code.Source("""
@@ -328,76 +261,6 @@
     session = config.initsession()
     l = getpassed(session)
     assert len(l) == 4
-    
-
-
-def test_documentation_virtual_collector_interaction():
-    rootdir = py.path.local(py.__file__).dirpath("doc")
-    # HACK 
-    from py.__.doc import conftest as conf
-    old = conf.option.forcegen
-    try:
-        conf.option.forcegen = 1
-        col = py.test2.collect.Directory(rootdir)
-        x = list(col._tryiter(yieldtype=py.test2.collect.Function))
-    finally:
-        conf.option.forcegen = old
-    
-
-def test__tryiter_ignores_skips():
-    tmp = py.test2.ensuretemp("_tryiterskip")
-    tmp.ensure("subdir", "conftest.py").write(py.code.Source("""
-        import py
-        class Directory(py.test2.collect.Directory):
-            def run(self):
-                py.test.skip("intentional")
-    """))
-    col = py.test2.collect.Directory(tmp)
-    try:
-        list(col._tryiter())
-    except KeyboardInterrupt: 
-        raise
-    except:
-        exc = py.code.ExceptionInfo() 
-        py.test2.fail("should not have raised: %s"  %(exc,))
-    
-    
-def test__tryiter_ignores_failing_collectors(): 
-    tmp = py.test2.ensuretemp("_tryiterfailing")
-    tmp.ensure("subdir", "conftest.py").write(py.code.Source("""
-        bla bla bla
-    """))
-    col = py.test2.collect.Directory(tmp)
-    try:
-        list(col._tryiter())
-    except KeyboardInterrupt: 
-        raise
-    except:
-        exc = py.code.ExceptionInfo() 
-        py.test2.fail("should not have raised: %s"  %(exc,))
-
-    l = []
-
-def test_tryiter_handles_keyboardinterrupt(): 
-    tmp = py.test2.ensuretemp("tryiterkeyboard")
-    tmp.ensure("subdir", "conftest.py").write(py.code.Source("""
-        raise KeyboardInterrupt() 
-    """))
-    col = py.test2.collect.Directory(tmp)
-    py.test2.raises(KeyboardInterrupt, list, col._tryiter())
-
-def test_check_random_inequality():
-    tmp = py.test2.ensuretemp("ineq")
-    tmp.ensure("test_x.py").write(py.code.Source("""def test_one():
-        pass
-    """))
-    col = py.test2.collect.Directory(tmp)
-    fn = col._tryiter().next()
-    assert fn != 3
-    assert fn != col
-    assert fn != [1,2,3]
-    assert [1,2,3] != fn
-    assert col != fn
 
 def test_check_generator_collect_problems():
     tmp = py.test2.ensuretemp("gener_coll")
@@ -434,33 +297,6 @@
     l = list(col._tryiter())
     assert not hasattr(col.obj, 'x')
 
-def test_check_collect_hashes():
-    tmp = py.test2.ensuretemp("check_collect_hashes")
-    tmp.ensure("test_one.py").write(py.code.Source("""
-        def test_1():
-            pass
-        
-        def test_2():
-            pass
-    """))
-    tmp.ensure("test_two.py").write(py.code.Source("""
-        def test_1():
-            pass
-        
-        def test_2():
-            pass
-    """))
-    tmp.ensure("__init__.py")
-    col = py.test2.collect.Directory(tmp)
-    l = list(col._tryiter())
-    assert len(l) == 4
-    for numi, i in enumerate(l):
-        for numj, j in enumerate(l):
-            if numj != numi:
-                assert hash(i) != hash(j)
-                assert i != j
-
-
 def test_check_directory_ordered():
     tmpdir = py.test2.ensuretemp("test_check_directory_ordered")
     fnames = []
@@ -477,40 +313,196 @@
     names = col.run()
     assert names == fnames 
 
-class TestCollectonly:
+def test_documentation_virtual_collector_interaction():
+    py.test.skip("figure out this test and rewrite independent of py/doc.")
+    rootdir = py.path.local(py.__file__).dirpath("doc")
+    # HACK 
+    from py.__.doc import conftest as conf
+    old = conf.option.forcegen
+    try:
+        conf.option.forcegen = 1
+        col = py.test2.collect.Directory(rootdir)
+        x = list(col._tryiter(yieldtype=py.test2.collect.Function))
+    finally:
+        conf.option.forcegen = old
+
+def test_check_random_inequality():
+    path = getexamplefile("funcexamples.py")
+    col = py.test2.collect.Module(path)
+    fn = col.join("funcpass")
+    assert fn != 3
+    assert fn != col
+    assert fn != [1,2,3]
+    assert [1,2,3] != fn
+    assert col != fn
+
+class Testgenitems: 
     def setup_class(cls):
-        tmp = py.test2.ensuretemp('itemgentest')
-        tmp.ensure("__init__.py")
-        tmp.ensure("test_one.py").write(py.code.Source("""
-        def test_one():
-            pass
+        cls.classtemp = py.test2.ensuretemp(cls.__name__)
+            
+    def setup_method(self, method):
+        self.tmp = self.classtemp.mkdir(method.func_name)
 
-        class TestX:
-            def test_method_one(self):
+    def _genitems(self, tmp=None):
+        if tmp is None:
+            tmp = self.tmp 
+        print "using tempdir", tmp 
+        config = py.test2.config._reparse([tmp])
+        l = eventappender(config)
+        items = list(genitems(config, config.getcolitems()))
+        return items, l 
+
+    def test_check_collect_hashes(self):
+        one = self.tmp.ensure("test_one.py")
+        one.write(py.code.Source("""
+            def test_1():
                 pass
 
-        class TestY(TestX):
-            pass
+            def test_2():
+                pass
         """))
-        tmp.ensure("test_two.py").write(py.code.Source("""
-        import py
-        py.test.skip('xxx')
+        one.copy(self.tmp.join("test_two.py"))
+        items, events = self._genitems()
+        assert len(items) == 4
+        for numi, i in enumerate(items):
+            for numj, j in enumerate(items):
+                if numj != numi:
+                    assert hash(i) != hash(j)
+                    assert i != j
+       
+    def test_skip_by_conftest_directory(self):
+        from py.__.test2 import outcome
+        self.tmp.ensure("subdir", "conftest.py").write(py.code.Source("""
+            import py
+            class Directory(py.test2.collect.Directory):
+                def run(self):
+                    py.test2.skip("intentional")
+        """))
+        items, events = self._genitems()
+        assert len(items) == 0
+        skips = [x for x in events
+                    if isinstance(x, repevent.CollectionFinish)
+                       and x.collector.name == 'subdir']
+        assert len(skips) == 1
+        assert skips[0].excinfo.errisinstance(outcome.Skipped)
+
+    def test_root_conftest_syntax_error(self): 
+        # do we want to unify behaviour with
+        # test_subdir_conftest_error? 
+        self.tmp.ensure("conftest.py").write("raise SyntaxError\n")
+        py.test2.raises(SyntaxError, self._genitems)
+       
+    def test_subdir_conftest_error(self):
+        self.tmp.ensure("sub", "conftest.py").write("raise SyntaxError\n")
+        items, events = self._genitems()
+        failures = [x for x in events 
+                        if isinstance(x, repevent.CollectionFinish)
+                           and x.excinfo]
+        assert len(failures) == 1
+        ev = failures[0] 
+        assert ev.excinfo.errisinstance(SyntaxError)
+    
+    def XXXtest_keyboardinterrupt(self): 
+        self.tmp.ensure("sub", "conftest.py").write("raise KeyboardInterrupt\n")
+        items, events = self._genitems()
+        assert 0
+
+    def test_skip_at_module_level(self):
+        self.tmp.ensure("test_module.py").write(py.code.Source("""
+            import py
+            py.test2.skip('xxx')
         """))
-        tmp.ensure("test_three.py").write("xxxdsadsadsadsa")
-        cls.tmp = tmp
+        items, events = self._genitems()
+        funcs = [x for x in items if isinstance(x, repevent.ItemStart)]
+        assert not funcs 
+        assert not items 
+        l = [x for x in events 
+                if isinstance(x, repevent.CollectionFinish)
+                   and x.collector.name == 'test_module.py']
+        assert len(l) == 1
+        ev = l[0]
+        assert ev.excinfo.errisinstance(outcome.Skipped) 
+
+    def test_example_items1(self):
+        self.tmp.ensure("test_example.py").write(py.code.Source('''
+            def test_one():
+                pass
+
+            class TestX:
+                def test_method_one(self):
+                    pass
 
-    def test_collectonly(self):
-        config = py.test2.config._reparse([self.tmp, '--collectonly'])
-        session = config.initsession()
-        # test it all in once
-        allevents = getevents_runmain(session)
-        started = finished = 0 
-        for event in allevents: 
-            assert not isinstance(event, repevent.ItemFinish)
-            if isinstance(event, repevent.CollectionStart):
-                started += 1      
-            elif isinstance(event, repevent.CollectionFinish):
-                finished += 1
+            class TestY(TestX):
+                pass
+        '''))
+        items, events = self._genitems()
+        assert len(items) == 3
+        assert items[0].name == 'test_one'
+        assert items[1].name == 'test_method_one'
+        assert items[2].name == 'test_method_one'
         
-        print started 
-        assert started == finished 
+    def test_custom_python_collection_from_conftest(self):
+        checkfile = setup_customconfigtest(self.tmp) 
+        for x in (self.tmp, checkfile, checkfile.dirpath()): 
+            items, events = self._genitems(x)
+            assert len(items) == 2
+            #assert items[1].__class__.__name__ == 'MyFunction'
+
+        return None # XXX shift below to session test? 
+        # test that running a session works from the directories
+        old = o.chdir() 
+        try: 
+            config = py.test2.config._reparse([]) 
+            session = config._getsessionclass()(config)
+            l = getpassed(session)
+            assert len(l) == 2
+        finally: 
+            old.chdir() 
+
+        # test that running the file directly works 
+        config = py.test2.config._reparse([str(checkfile)]) 
+        session = config._getsessionclass()(config)
+        l = getpassed(session) 
+        assert len(l) == 2
+
+
+    def test_custom_NONpython_collection_from_conftest(self):
+        checkfile = setup_non_python_dir(self.tmp)
+       
+        for x in (self.tmp, checkfile, checkfile.dirpath()): 
+            print "checking that %s returns custom items" % (x,) 
+            items, events = self._genitems(x)
+            assert len(items) == 1
+            assert items[0].__class__.__name__ == 'CustomItem'
+
+        return None # XXX shift below to session tests? 
+
+        # test that running a session works from the directories
+        old = self.tmp.chdir() 
+        try: 
+            l = getpassed(config.initsession())
+            assert len(l) == 1
+        finally:
+            old.chdir() 
+
+        # test that running the file directly works 
+        config = py.test2.config._reparse([str(checkfile)]) 
+        session = config._getsessionclass()(config)
+        l = getpassed(session) 
+        assert len(l) == 1
+
+    def test_collect_doctest_files_with_test_prefix(self):
+        self.tmp.ensure("whatever.txt")
+        checkfile = self.tmp.ensure("test_something.txt")
+        checkfile.write(py.code.Source("""
+            alskdjalsdk
+            >>> i = 5
+            >>> i-1
+            4
+        """))
+        for x in (self.tmp, checkfile): 
+            #print "checking that %s returns custom items" % (x,) 
+            items, events = self._genitems(x)
+            assert len(items) == 1
+            assert isinstance(items[0], DoctestText)
+

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	Tue Feb 12 18:06:06 2008
@@ -22,23 +22,3 @@
     """)
     py.test2.raises(Failed, "testitem.run()")
    
-
-def test_collect_doctest_files_with_test_prefix():
-    o = py.test2.ensuretemp("testdoctest")
-    checkfile = o.ensure("test_something.txt")
-    o.ensure("whatever.txt")
-    checkfile.write(py.code.Source("""
-        alskdjalsdk
-        >>> i = 5
-        >>> i-1
-        4
-    """))
-    for x in (o, checkfile): 
-        #print "checking that %s returns custom items" % (x,) 
-        config = py.test2.config._reparse([x])
-        col = config._getcollector(x)
-        items = list(col._tryiter(py.test2.collect.Item))
-        assert len(items) == 1
-        assert isinstance(items[0], DoctestText)
-   
-     

Modified: py/branch/event/py/test2/testing/test_executor.py
==============================================================================
--- py/branch/event/py/test2/testing/test_executor.py	(original)
+++ py/branch/event/py/test2/testing/test_executor.py	Tue Feb 12 18:06:06 2008
@@ -80,7 +80,7 @@
         assert not outcome.excinfo 
 
     def test_box_executor_stdout(self):
-        item = self.getexample("print")
+        item = self.getfunc("print")
         ex = BoxExecutor(item, config=self.config)
         outcome_repr = ex.execute()
         outcome = ReprOutcome(outcome_repr)
@@ -88,7 +88,7 @@
         assert outcome.stdout.find("samfing") != -1
 
     def test_box_executor_stdout_error(self):
-        item = self.getexample("printfail")
+        item = self.getfunc("printfail")
         ex = BoxExecutor(item, config=self.config)
         outcome_repr = ex.execute()
         outcome = ReprOutcome(outcome_repr)
@@ -96,7 +96,7 @@
         assert outcome.stdout.find("samfing elz") != -1 
 
     def test_cont_executor(self):
-        item = self.getexample("printfail")
+        item = self.getfunc("printfail")
         ex = AsyncExecutor(item, config=self.config)
         cont, pid = ex.execute()
         assert pid

Modified: py/branch/event/py/test2/testing/test_remote.py
==============================================================================
--- py/branch/event/py/test2/testing/test_remote.py	(original)
+++ py/branch/event/py/test2/testing/test_remote.py	Tue Feb 12 18:06:06 2008
@@ -1,7 +1,9 @@
 import py
-from py.__.test2.testing.setupdata import setup_module
 from test_session import getevents_runmain
 
+def setup_module(mod):
+    mod.tmpdir = py.test.ensuretemp(mod.__name__) 
+
 class TestRemote: 
     def test_exec(self): 
         o = tmpdir.ensure('remote', dir=1) 

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	Tue Feb 12 18:06:06 2008
@@ -1,11 +1,14 @@
 import py
-from setupdata import setup_module # sets up global 'tmpdir' 
+from setupdata import getexamplefile 
 from py.__.test2.outcome import Skipped, Failed, Passed, Outcome
 from py.__.test2.terminal.out import getout
 from py.__.test2 import repevent 
 
 from test_session2 import getevents_runmain
 
+def setup_module(mod):
+    mod.tmpdir = py.test.ensuretemp(mod.__name__) 
+
 implied_options = {
     '-v': 'verbose', 
     '-l': 'showlocals',
@@ -29,8 +32,10 @@
            [i for i in all if isinstance(i, repevent.DeselectedTest)]
 
 def getfailed(all):
-    return [i for i in getoutcomes(all) if i.failed] + \
-           [i for i in all 
+    return [i for i in getoutcomes(all) if i.failed]
+
+def getfailedcollections(all):
+    return [i for i in all 
                 if isinstance(i, repevent.CollectionFinish) and 
                     i.excinfo]
 
@@ -41,7 +46,8 @@
 
 def check_conflict_option(opts):
     print "testing if options conflict:", " ".join(opts)
-    config = py.test2.config._reparse(opts + [datadir/'filetest.py'])
+    path = getexamplefile("filetest.py")
+    config = py.test2.config._reparse(opts + [path])
     py.test2.raises((ValueError, SystemExit), """
         config.initsession()
     """)
@@ -51,32 +57,35 @@
         yield check_implied_option, [key], expr
 
 def check_implied_option(opts, expr):
-    config = py.test2.config._reparse(opts + [datadir/'filetest.py'])
+    path = getexamplefile("filetest.py")
+    config = py.test2.config._reparse(opts + [path])
     session = config.initsession()
     assert eval(expr, session.config.option.__dict__)
 
 def test_default_session_options():
+    path = getexamplefile("filetest.py")
     for opts in ([], ['-l'], ['-s'], ['--tb=no'], ['--tb=short'], 
                  ['--tb=long'], ['--fulltrace'], ['--nomagic'], 
                  ['--traceconfig'], ['-v'], ['-v', '-v']):
-        yield runfiletest, opts
+        yield runfiletest, opts + [path]
 
 def runfiletest(opts):
-    config = py.test2.config._reparse(opts + [datadir/'filetest.py'])
+    config = py.test2.config._reparse(opts) 
     session = config.initsession()
     all = getevents_runmain(session)
     assert len(getfailed(all)) == 2 
     assert not getskipped(all)
 
 def test_is_not_boxed_by_default():
-    config = py.test2.config._reparse([datadir])
+    path = getexamplefile("filetest.py")
+    config = py.test2.config._reparse([path])
     assert not config.option.boxed
 
 class TestKeywordSelection: 
     def test_select_simple(self):
         def check(keyword, name):
-            config = py.test2.config._reparse([datadir/'filetest.py', 
-                                                   '-s', '-k', keyword])
+            p = getexamplefile("filetest.py")
+            config = py.test2.config._reparse([p, '-s', '-k', keyword])
             session = config._getsessionclass()(config)
             all = getevents_runmain(session) 
             outcomes = [i for i in all if isinstance(i, repevent.ItemFinish)]
@@ -90,7 +99,7 @@
         check('TestClass.test', 'test_method_one')
 
     def test_select_extra_keywords(self):
-        o = tmpdir.ensure('selecttest', dir=1)
+        o = tmpdir.ensure('test_select_extra_keywords', dir=1) 
         tfile = o.join('test_select.py').write(py.code.Source("""
             def test_1():
                 pass 
@@ -118,8 +127,8 @@
             assert l[0].item.name == 'test_1'
 
     def test_select_starton(self):
-        config = py.test2.config._reparse([datadir/'testmore.py', 
-                                          '-j', '-k', "test_two"])
+        p = getexamplefile("testmore.py")
+        config = py.test2.config._reparse([p, '-j', '-k', "test_two"])
         session = config._getsessionclass()(config)
         all = getevents_runmain(session)
         assert len(getpassed(all)) == 2
@@ -136,21 +145,23 @@
         return session, all
 
     def test_terminal(self): 
-        session, all = self.mainsession(datadir / 'filetest.py')
+        p = getexamplefile("filetest.py") 
+        session, all = self.mainsession(p) 
         outcomes = getoutcomes(all)
         assert len(getfailed(all)) == 2
 
     def test_syntax_error_module(self): 
-        session, all = self.mainsession(datadir / 'syntax_error.py')
-        l = getfailed(all)
+        p = getexamplefile("syntax_error.py")
+        session, all = self.mainsession(p) 
+        l = getfailedcollections(all)
         assert len(l) == 1
         out = l[0].excinfo.exconly()
         assert out.find(str('syntax_error.py')) != -1
         assert out.find(str('not python')) != -1
 
     def test_exit_first_problem(self): 
-        session, all = self.mainsession("--exitfirst", 
-                                        datadir / 'filetest.py')
+        p = getexamplefile("filetest.py")
+        session, all = self.mainsession("--exitfirst", p) 
         assert session.config.option.exitfirst
         assert len(getfailed(all)) == 1 
         assert not getpassed(all)
@@ -164,7 +175,7 @@
         """))
         session, all = self.mainsession(o) 
         #print out
-        failures = getfailed(all)
+        failures = getfailedcollections(all)
         out = failures[0].excinfo.exconly()
         i = out.find('TypeError') 
         assert i != -1 
@@ -258,16 +269,14 @@
             a = 1
         """))
         session, all = self.mainsession(o)
-        l = getfailed(all)
+        l = getfailedcollections(all)
         assert len(l) == 1 
         out = l[0].excinfo.exconly()
         assert out.find('does_not_work') != -1 
 
     def test_safe_repr(self):
-        session, all = self.mainsession(datadir/'brokenrepr.py')
-        #print 'Output of simulated "py.test2 brokenrepr.py":'
-        #print all
-
+        p = getexamplefile("brokenrepr.py")
+        session, all = self.mainsession(p) 
         l = getfailed(all)
         assert len(l) == 2
         out = l[0].excinfo.exconly()
@@ -275,3 +284,41 @@
         out = l[1].excinfo.exconly()
         assert out.find("[unknown exception raised in repr()]") != -1
         
+class TestCollectonly:
+    def setup_class(cls):
+        tmp = py.test2.ensuretemp('itemgentest')
+        tmp.ensure("__init__.py")
+        tmp.ensure("test_one.py").write(py.code.Source("""
+        def test_one():
+            pass
+
+        class TestX:
+            def test_method_one(self):
+                pass
+
+        class TestY(TestX):
+            pass
+        """))
+        tmp.ensure("test_two.py").write(py.code.Source("""
+        import py
+        py.test.skip('xxx')
+        """))
+        tmp.ensure("test_three.py").write("xxxdsadsadsadsa")
+        cls.tmp = tmp
+
+    def test_collectonly(self):
+        config = py.test2.config._reparse([self.tmp, '--collectonly'])
+        session = config.initsession()
+        # test it all in once
+        allevents = getevents_runmain(session)
+        started = finished = 0 
+        for event in allevents: 
+            assert not isinstance(event, repevent.ItemFinish)
+            if isinstance(event, repevent.CollectionStart):
+                started += 1      
+            elif isinstance(event, repevent.CollectionFinish):
+                finished += 1
+        
+        print started 
+        assert started == finished 
+



More information about the pytest-commit mailing list