Fresco/test/syunit output.py,NONE,1.1 syn2cc.py,NONE,1.1

Nathaniel Smith <[email protected]>
Newsgroups gmane.comp.video.fresco.cvs
Message-ID <[email protected]>
Update of /cvs/fresco/Fresco/test/syunit
In directory purcel:/tmp/cvs-serv16654/test/syunit

Added Files:
	output.py syn2cc.py 
Log Message:
The basic unit test infrastructure... now we just need build
system support...


--- NEW FILE: output.py ---
# -*- python -*-
#                           Package   : omniidl
# output.py                 Created on: 1999/10/27
#			    Author    : Duncan Grisby (dpg1)
#
#    Copyright (C) 1999 AT&T Laboratories Cambridge
#
#  This file is part of omniidl.
#
#  omniidl is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
#  02111-1307, USA.
#
# Description:
#
#   IDL compiler output functions

"""Output stream

Class:

  Stream -- output stream which outputs templates, performing
            key/value substitution and indentation."""

import string

def dummy(): pass

StringType = type("")
FuncType   = type(dummy)

class Stream:
    """IDL Compiler output stream class

The output stream takes a template string containing keys enclosed in
'@' characters and replaces the keys with their associated values. It
also provides counted indentation levels.

  eg. Given the template string:

    template = \"\"\"\\
class @id@ {
public:
  @id@(@type@ a) : a_(a) {}

private:
  @type@ a_;
};\"\"\"

  Calling s.out(template, id="foo", type="int") results in:

    class foo {
    public:
      foo(int a) : a_(a) {}

    private:
      int a_;
    };


Functions:

  __init__(file, indent_size)   -- Initialise the stream with the
                                   given file and indent size.
  inc_indent()                  -- Increment the indent level.
  dec_indent()                  -- Decrement the indent level.
  out(template, key=val, ...)   -- Output the given template with
                                   key/value substitution and
                                   indenting.
  niout(template, key=val, ...) -- As out(), but with no indenting."""


    def __init__(self, file, indent_size = 2):
        self.file        = file
        self.indent_size = indent_size
        self.indent      = 0
        self.do_indent   = 1

    def inc_indent(self): self.indent = self.indent + self.indent_size
    def dec_indent(self): self.indent = self.indent - self.indent_size

    def out(self, text, ldict={}, **dict):
        """Output a multi-line string with indentation and @@ substitution."""

        dict.update(ldict)

        pos    = 0
        tlist  = string.split(text, "@")
        ltlist = len(tlist)
        i      = 0
        while i < ltlist:

            # Output plain text
            pos = self.olines(pos, self.indent, tlist[i])

            i = i + 1
            if i == ltlist: break

            # Evaluate @ expression
            try:
                expr = dict[tlist[i]]
            except:
                # If a straight look-up failed, try evaluating it
                if tlist[i] == "":
                    expr = "@"
                else:
                    expr = eval(tlist[i], globals(), dict)

            if type(expr) is StringType:
                pos = self.olines(pos, pos, expr)
            elif type(expr) is FuncType:
                oindent = self.indent
                self.indent = pos
                apply(expr)
                self.indent = oindent
            else:
                pos = self.olines(pos, pos, str(expr))

            i = i + 1

        self.odone()

    def niout(self, text, ldict={}, **dict):
        """Output a multi-line string without indentation."""

        dict.update(ldict)

        pos    = 0
        tlist  = string.split(text, "@")
        ltlist = len(tlist)
        i      = 0
        while i < ltlist:

            # Output plain text
            pos = self.olines(pos, 0, tlist[i])

            i = i + 1
            if i == ltlist: break

            # Evaluate @ expression
            try:
                expr = dict[tlist[i]]
            except:
                # If a straight look-up failed, try evaluating it
                if tlist[i] == "":
                    expr = "@"
                else:
                    expr = eval(tlist[i], globals(), dict)

            if type(expr) is StringType:
                pos = self.olines(pos, pos, expr)
            elif type(expr) is FuncType:
                oindent = self.indent
                self.indent = pos
                apply(expr)
                self.indent = oindent
            else:
                pos = self.olines(pos, pos, str(expr))

            i = i + 1

        self.odone()


    def olines(self, pos, indent, text):
        istr  = " " * indent
        write = self.file.write

        stext = string.split(text, "\n")
        lines = len(stext)
        line  = stext[0]

        if self.do_indent:
            pos = indent
            write(istr)

        write(line)

        for i in range(1, lines):
            line = stext[i]
            write("\n")
            if line:
                pos = indent
                write(istr)
                write(line)

        if lines > 1 and not line: # Newline at end of text
            self.do_indent = 1
            return self.indent

        self.do_indent = 0
        return pos + len(line)

    def odone(self):
        self.file.write("\n")
        self.do_indent = 1


class StringStream(Stream):
    """Writes to a string buffer rather than a file."""
    def __init__(self, indent_size = 2):
        Stream.__init__(self, self, indent_size)
        self.buffer = []

    def write(self, text):
        self.buffer.append(text)

    def __str__(self):
        return string.join(self.buffer, "")

--- NEW FILE: syn2cc.py ---
#!/usr/bin/env python
# My experimental, rough-draft-but-functional, unit test harness generator
# Usage:  $0 foo.syn foo.cc
# Copyright (C) 2002  Nathaniel Smith <[email protected]>

import re
import sys
from cStringIO import StringIO

# to process a tree, we take it from the linker, and we run our processor over
# it, building up a list of test to run
#
# Then we dump them all out again.
# In the future this should be refactored to be more general and more
# powerful, so that we can have a language-neutral core that does clever
# things to figure out the structure of tests (paying attention to all sorts
# of stuff -- tag extraction, dependency checking, etc.), and then modules
# that use this generate language- and build-system-specific harnesses.

from Synopsis.Core import AST
import output  # our local copy of omniidl.output
ExpandingStream = output.Stream
ExpandingStringStream = output.StringStream

"""The class that all test classes inherit from.  This is how we find test
classes.  (We should also support a @is_test_class tag or something, for
classes that we're unable to detect this inheritance for (or don't actually
inherit at all.  Ideally, we should also detect when we neither inherit from
test_class_root nor have the @is_test_class tag, but do inherit from something
that does have the @is_test_class tag.
"""
test_class_root = ("Fresco_Test", "TestCase")

test_file_tmpl = """\
/* This file was automatically generated.  Do not edit! */
#include <TestCmd.hh>
#include <TestCase.hh>
#include <TestCaseWrapper.hh>

@test_class_includes@

int main(char argc, char** argv)
{
    Fresco_Test::TestCmd testcmd(argc, argv);
    Fresco_Test::TestCaseWrapper* test;
  
@all_tests@

  return testcmd.run();
}
"""

test_include_tmpl = """#include "@test_class_file@"
"""

single_test_tmpl = """test = new Fresco_Test::TestCaseWrapperImpl< @test_class@ >
    (// name of test
     "@name@",
     // test method to call
     &@test_class@::@method@,
     // description of this test
     "@desc@"
     );
testcmd.add(test);
"""

class ParsedTestMethod:
    def __init__(self, method_name, test_name, test_desc):
        self.__method_name = method_name
        self.__test_name = test_name
        self.__test_desc = test_desc
    def method_name(self):
        return self.__method_name
    def test_name(self):
        return self.__test_name
    def test_desc(self):
        return self.__test_desc

class ParsedTestClass:
    def __init__(self, class_name, file_name):
        self.__class_name = class_name
        self.__file_name = file_name
        self.__test_methods = []
    def add_test_method(self, method_name):
        self.__test_methods.append(method_name)
    def class_name(self):
        return self.__class_name
    def file_name(self):
        return self.__file_name
    def methods(self):
        return self.__test_methods

class FindTestsVisitor(AST.Visitor):
    def __init__(self, base_class):
        self.base_class = base_class
        self.in_test_class = 0
        self.current_class = None
        self.classes = []

    def visitClass(self, node):
        # looking at an AST.Class
        # figure out if this class inherits from base_class
        # probably this will broken on embedded classes -- how do we tell when
        # we exit a class scope?
        file_name = node.file()
        class_name = "::".join(node.name())
        parent_names = [n.parent().name() for n in node.parents()]
        print "Parent names of class %s (in %s): %s" % (class_name,
                                                        file_name,
                                                        `parent_names`)
        if self.base_class in parent_names:
            print "Ah-hah, gotcha!"
            self.in_test_class = 1
            self.current_class = ParsedTestClass(class_name, file_name)
            self.classes.append(self.current_class)
            if node.template():
                self.in_test_class = 0
                print "Warning: ignoring template class " + class_name
                return
            for declaration in node.declarations():
                declaration.accept(self)
        
    def visitOperation(self, node):
        if not self.in_test_class:
            return
        method = ParsedTestMethod(node.realname()[-1],
                                  node.realname()[-1],
                                  "Description goes here")
        self.current_class.add_test_method(method)

    def get_classes(self):
        return self.classes


def fill_template_from_ast(ast, outstream):
    visitor = FindTestsVisitor(test_class_root)
    visitor.visitAST(ast)
    test_files = []
    test_stream = ExpandingStringStream()
    test_stream.inc_indent()
    for tclass in visitor.get_classes():
        if tclass.file_name() not in test_files:
            test_files.append(tclass.file_name())
        class_name = tclass.class_name()
        for method in tclass.methods():
            test_stream.out(single_test_tmpl,
                            name=quote_for_cxx(method.test_name()),
                            test_class=tclass.class_name(),
                            method=method.method_name(),
                            desc=quote_for_cxx(method.test_desc()))

    include_stream = ExpandingStringStream()
    for file in test_files:
        include_stream.out(test_include_tmpl, test_class_file=file)
    
    ex_outstream = ExpandingStream(outstream)
    ex_outstream.out(test_file_tmpl,
                     test_class_includes=include_stream,
                     all_tests=test_stream)

# inefficient and incomplete, but should work well enough
def quote_for_cxx(str):
    """Quote a string so it can be written into a C++ source file."""
    str = re.sub(r"(\\|\")", r"\\\1", str)
    str = re.sub(r"\n", r"\\n", str)
    str = re.sub(r"\t", r"\\t", str)
    return str

def usage():
    print "Usage: %s astfile.syn outfile.cc" % sys.argv[0]

def main():
    if len(sys.argv) != 3:
        usage()
        return
#    fill_template_from_ast(AST.load(sys.argv[1]), open(sys.argv[2], "w"))
    fill_template_from_ast(AST.load(sys.argv[1]), sys.stdout)

if __name__ == "__main__":
    main()
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.