[py-svn] r33460 - in py/dist/py/test/tracer: . testing

guido at codespeak.net guido at codespeak.net
Thu Oct 19 16:20:11 CEST 2006


Author: guido
Date: Thu Oct 19 16:20:08 2006
New Revision: 33460

Modified:
   py/dist/py/test/tracer/genrest.py
   py/dist/py/test/tracer/testing/test_rest.py
Log:
Removed the 'write_interface()' method as there was no need for another layer
of abstraction there. Enabled linking to files and refined link writers. Some
rendering details (header sizes, etc.) and cleanups (removed more commented
code, etc.).


Modified: py/dist/py/test/tracer/genrest.py
==============================================================================
--- py/dist/py/test/tracer/genrest.py	(original)
+++ py/dist/py/test/tracer/genrest.py	Thu Oct 19 16:20:08 2006
@@ -49,20 +49,26 @@
     """ No-link writer (inliner)
     """
     def getlink(self, filename, lineno):
-        return (py.path.local(filename).open().readlines()[lineno-1], "")
+        return ('%s:%s' % (filename, lineno), "")
+
+class DirectFS(AbstractLinkWriter):
+    """ Creates links to the files on the file system (for local docs)
+    """
+    def getlink(self, filename, lineno):
+        return ('%s:%s' % (filename, lineno), 'file://%s' % (filename,))
 
 class PipeWriter(object):
     def __init__(self, output=sys.stdout):
         self.output = output
     
     def write_section(self, name, data):
-        text = "Written file: %s.txt" % (name,)
+        text = "Contents of file %s.txt:" % (name,)
         self.output.write(text + "\n")
         self.output.write("=" * len(text) + "\n")
         self.output.write("\n")
         self.output.write(data + "\n")
 
-    def rewrite_link(self, type, targetname, targetfilename):
+    def getlink(self, type, targetname, targetfilename):
         return '%s.txt' % (targetfilename,)
 
 class DirWriter(object):
@@ -76,7 +82,7 @@
         filename = '%s.txt' % (name,)
         self.directory.ensure(filename).write(data)
 
-    def rewrite_link(self, type, targetname, targetfilename):
+    def getlink(self, type, targetname, targetfilename):
         # we assume the result will get converted to HTML...
         return '%s.html' % (targetfilename,)
 
@@ -84,13 +90,16 @@
     def __init__(self, fpath):
         self.fpath = fpath
         self.fp = fpath.open('w+')
+        self._defined_targets = []
 
     def write_section(self, name, data):
         self.fp.write(data)
         self.fp.flush()
 
-    _defined_targets = []
-    def rewrite_link(self, type, targetname, targetbasename):
+    def getlink(self, type, targetname, targetbasename):
+        # XXX problem: because of docutils' named anchor generation scheme,
+        # a method Foo.__init__ would clash with Foo.init (underscores are 
+        # removed)
         if targetname in self._defined_targets:
             return None
         self._defined_targets.append(targetname)
@@ -104,11 +113,11 @@
         self.writer = writer
     
     def write(self):
-        # first write down a file with all the exported interfaces,
-        # sorted by type
-        self.write_interface()
-    
-    def write_interface(self):
+        """write the data to the writer"""
+        # note that this builds up a list of Rest elements for the index as
+        # 'side effect', the list is passed along and filled, while the actual
+        # sections (also ReST elements) are returned by the write_* methods
+        # XXX this is quite icky! would be nice to have refactored
         indexlst = [Title("Module: %s" % self.dsa.get_module_name(),
                           belowchar="="),
                     Paragraph(self.dsa.get_module_info()),
@@ -130,7 +139,7 @@
         retlst = []
         for name in self.dsa.get_function_names():
             sectionname = 'function_%s' % (name,)
-            linktarget = self.writer.rewrite_link('function', name,
+            linktarget = self.writer.getlink('function', name,
                                                   sectionname)
             indexlst.append(ListItem(Text("Function: "),
                                 Link(name, linktarget)))
@@ -142,7 +151,7 @@
         retlst = []
         for name in self.dsa.get_class_names():
             sectionname = 'class_%s' % (name,)
-            linktarget = self.writer.rewrite_link('class', name, sectionname)
+            linktarget = self.writer.getlink('class', name, sectionname)
             indexlst.append(ListItem(Text("Class: "), Link(name, linktarget)))
             retlst.append((sectionname, self.write_class(sectionname, name)))
         return retlst
@@ -157,14 +166,14 @@
         for method in self.dsa.get_class_methods(class_name):
             sectionname = 'method_%s_%s' % (class_name, method)
             linktext = '%s.%s' % (class_name, method)
-            linktarget = self.writer.rewrite_link('function', linktext,
+            linktarget = self.writer.getlink('function', linktext,
                                                   sectionname)
             classlst.append(ListItem(Link(linktext, linktarget)))
             # XXX assuming a function is always part of a class section
             funclist.append((sectionname,
                              self.write_function(sectionname,
                                                  class_name + "." + method,
-                                                 '+')))
+                                                 '^')))
         return classlst, funclist
     
     def write_function(self, section_name, fun_name, belowchar='-'):
@@ -175,7 +184,14 @@
                BlockQuote(self.dsa.get_function_doc(fun_name)),
                BlockQuote(self.dsa.get_function_definition(fun_name))]
         
-        lst.append(Paragraph("Function source: XXX (to write a link here)"))
+        # XXX missing implementation of dsa.get_function_location()
+        #filename, lineno = self.dsa.get_function_location(fun_name)
+        #linkname, linktarget = self.linkgen.getlink(filename, lineno)
+        #if linktarget:
+        #    lst.append(Paragraph("Function source: ",
+        #               Link(linkname, linktarget)))
+        #else:
+        lst.append(Paragraph('Function source: <unknown>'))
         
         args, retval = self.dsa.get_function_signature(fun_name)
         # XXX: we just do "knowntype" here, but we should
@@ -188,29 +204,28 @@
         lst.append(arg_quote)
         
         # call sites..
-        call_site_title = Title("Call sites:", belowchar=belowchar)
+        call_site_title = Title("Call sites:", belowchar='^')
         lst.append(call_site_title)
         call_sites = lst
         
         for call_site, frame in self.dsa.get_function_callpoints(fun_name):
             link_str = "File %s:%s" % (call_site.filename,
                                        call_site.lineno)
-            #link_str, link_target = self.linkgen.getlink(call_site.filename,
-            #                                             call_site.lineno)
-            #if link_target: # otherwise it's just inline text
-            #    call_sites.append(Paragraph(Link(link_str, link_target)))
-            #else:
-            #    call_sites.append(Paragraph(link_str))
+            link_str, link_target = self.linkgen.getlink(call_site.filename,
+                                                         call_site.lineno)
+            if link_target: # otherwise it's just inline text
+                call_sites.append(Paragraph(Link(link_str, link_target)))
+            else:
+                call_sites.append(Paragraph(link_str))
             #call_sites.append(BlockQuote(call_site.source))
             # XXX: For now, we just paste here the filename of that
-            call_sites.append(Paragraph(link_str))
+            #call_sites.append(Paragraph(link_str))
             source = frame.code.source()
             lines = []
             for num, line in enumerate(source):
                 if num == call_site.lineno - frame.code.firstlineno - 1:
                     m = re.match("^( *)(.*)", line)
-                    lines.append("%s >%s%s" % (num, "-" * len(m.group(1)),
-                                               m.group(2)))
+                    lines.append(">%s%s" % ("-" * len(m.group(1)), m.group(2)))
                 else:
                     lines.append(" " + line)
             call_sites.append(BlockQuote("\n".join(lines)))

Modified: py/dist/py/test/tracer/testing/test_rest.py
==============================================================================
--- py/dist/py/test/tracer/testing/test_rest.py	(original)
+++ py/dist/py/test/tracer/testing/test_rest.py	Thu Oct 19 16:20:08 2006
@@ -3,13 +3,14 @@
 """
 
 import py
+from StringIO import StringIO
 
 try:
     from py.__.test.tracer.genrest import ViewVC, RestGen, PipeWriter, \
-                                            DirWriter, FileWriter, DirectPaste
+                                            DirWriter, FileWriter, \
+                                            DirectPaste, DirectFS
     from py.__.test.tracer.tracer import DocStorage, Tracer
 
-    from StringIO import StringIO
     from py.__.test.tracer.testing.runtest import cut_pyc
 except ImportError, s:
     py.test.skip("Cannot import: %s" % str(s))
@@ -17,12 +18,6 @@
 def setup_module(mod):
     mod.temppath = py.test.ensuretemp('restgen')
 
-def test_links():
-    vcview = ViewVC("http://codespeak.net/viewvc/")
-    _, linkname = vcview.getlink(cut_pyc(__file__), 0)
-    assert linkname == ('http://codespeak.net/viewvc/py/test/tracer/'
-                        'testing/test_rest.py?view=markup')
-
 class SomeClass(object):
     """Some class definition"""
     
@@ -52,19 +47,75 @@
     """
     return "d"
 
-def test_dir_writer():
-    p = StringIO()
-    dir = temppath.ensure("dirwriter", dir=True)
-    w = DirWriter(dir)
-    w.write_section("one", "one data")
-    w.write_section("two", "two data")
-    assert dir.join("one.txt").read() == "one data"
-    assert dir.join("two.txt").read() == "two data"
-
 def test_direct_link():
-    assert DirectPaste().getlink(cut_pyc(__file__), 2)[0] == (
-        '""" tests document generation\n')
-    # C-c C-v ....
+    fname = cut_pyc(__file__)
+    title, link = DirectPaste().getlink(fname, 2)
+    assert title == '%s:%s' % (fname, 2)
+    assert link == ''
+
+def test_viewvc_link():
+    vcview = ViewVC("http://codespeak.net/viewvc/")
+    fname = cut_pyc(__file__)
+    title, link = vcview.getlink(fname, 0)
+    assert title == '%s:%s' % (fname, 0)
+    assert link == ('http://codespeak.net/viewvc/py/test/tracer/'
+                        'testing/test_rest.py?view=markup')
+
+def test_fs_link():
+    title, link = DirectFS().getlink('/foo/bar/baz.py', 100)
+    assert title == '/foo/bar/baz.py:100'
+    assert link == 'file:///foo/bar/baz.py'
+
+class WriterTest(object):
+    def get_filled_writer(self, writerclass, *args, **kwargs):
+        dw = writerclass(*args, **kwargs)
+        dw.write_section('foo', 'foo data')
+        dw.write_section('bar', 'bar data')
+        return dw
+
+class TestDirWriter(WriterTest):
+    def test_write_section(self):
+        tempdir = temppath.ensure('dirwriter', dir=True)
+        dw = self.get_filled_writer(DirWriter, tempdir)
+        fpaths = tempdir.listdir('*.txt')
+        assert len(fpaths) == 2
+        assert sorted([f.basename for f in fpaths]) == ['bar.txt', 'foo.txt']
+        assert tempdir.join('foo.txt').read() == 'foo data'
+        assert tempdir.join('bar.txt').read() == 'bar data'
+    
+    def test_getlink(self):
+        dw = DirWriter(temppath.join('dirwriter_getlink'))
+        link = dw.getlink('function', 'Foo.bar', 'method_foo_bar')
+        assert link == 'method_foo_bar.html'
+
+class TestFileWriter(WriterTest):
+    def test_write_section(self):
+        tempfile = temppath.ensure('filewriter', file=True)
+        fw = self.get_filled_writer(FileWriter, tempfile)
+        data = tempfile.read()
+        assert len(data)
+    
+    def test_getlink(self):
+        fw = FileWriter(temppath.join('filewriter_getlink'))
+        link = fw.getlink('function', 'Foo.bar', 'method_foo_bar')
+        assert link == '#function-foo-bar'
+        # only produce the same link target once...
+        link = fw.getlink('function', 'Foo.bar', 'method_foo_bar')
+        assert link is None
+        link = fw.getlink('function', 'Foo.__init__', 'method_foo___init__')
+        assert link == '#function-foo-init'
+
+class TestPipeWriter(WriterTest):
+    def test_write_section(self):
+        s = StringIO()
+        pw = self.get_filled_writer(PipeWriter, s)
+        data = s.getvalue()
+        assert len(data)
+
+    def test_getlink(self):
+        pw = PipeWriter(StringIO())
+        link = pw.getlink('function', 'Foo.bar', 'method_foo_bar')
+        assert link == 'method_foo_bar.txt'
 
 class TestRest(object):
     def get_filled_docstorage(self):
@@ -76,7 +127,7 @@
         t.start_tracing()
         s1 = SomeClass("a")
         fun(1, 2, s1)
-        s2 = SomeClass("b")
+        s2 = SomeSubClass("b")
         s2.method(1,2,3)
         fun(1, 3, s2)
         t.end_tracing()
@@ -109,7 +160,7 @@
 
     def test_check_internal_links(self):
         ds = self.get_filled_docstorage()
-        lg = DirectPaste()
+        lg = DirectFS()
         tempdir = temppath.ensure('internal_links', dir=True)
         r = RestGen(ds, lg, DirWriter(tempdir))
         r.write()
@@ -130,6 +181,8 @@
     def test_check_section_order(self):
         # we use the previous method's data
         tempfile = temppath.join('internal_links.txt')
+        if not tempfile.check():
+            py.test.skip('depends on previous test, which failed')
         data = tempfile.read()
         # index should be above the rest
         assert data.find('Exported classes:') > -1
@@ -146,20 +199,3 @@
         # assert data.find('Function: SomeClass.__init__') < data.find(
         #                                     'Function: SomeClass.method')
 
-##def test_generation():
-##    py.test.skip("WIP")
-##    descs = {"fun":fun}
-##    ds = DocStorage().from_dict(descs)
-##    lg = ViewVC("http://codespeak.net/viewvc/")
-##    t = Tracer(ds)
-##    t.start_tracing()
-##    fun(1, ("g", 3), 8)
-##    fun(2., ("a", 1.), "a")
-##    t.end_tracing()
-##    s = StringIO()
-##    r = RestGen(ds, lg, output=s)
-##    r.write()
-##    # we cannot check the source, cause the rapidly changing
-##    # visual effect will break it, so we'll make assertion later
-##    # XXX: do that
-##    assert s.getvalue()



More information about the pytest-commit mailing list