comtest
Class ComTest

java.lang.Object
  extended by comtest.ComTest

public class ComTest
extends java.lang.Object

A class for making testing easy. Reads the files given in parameters and generates JUNIT tests from comments.

The idea is to simplify writing unit tests. And to get unit test as examples to comments and JavaDoc. That's where the name ComTest comes (Comments for Testing)

 Example: Just simple initialization section:
 
 Counter cnt = new Counter(3);                            // IS
              cnt.getCount() === 0;  cnt.getSum() === 0;  // IS
 cnt.add(1);  cnt.getCount() === 1;  cnt.getSum() === 1;  // IS
 cnt.add(2);  cnt.getCount() === 2;  cnt.getSum() === 3;  // IS
 
 Syntax:
   The ComTest comment must be inside block comments 
   and start with
     (at)example
     [pre name="testModuleName"]  // change [] to HTML <> 
   and ends with 
     [/pre]
     
   Before handling the ComTest line, comments after //
   is removed.
     
   The test itself contains following sections
    0) The test case name is taken from pre-tag.
    
       Or if there is only name="test" then name is
       found from the next starting class or method
       and the the test case names comes like
         testAdd34
       where 34 is the line of the add-methods heading.     
   
    1) Initialization section.                           (IS)
       This is Java code until first template section
       
    2) Template section                                  (TS)
       This is Java-code where at least one $ exists
       on the line outside of quotes. 
       Template code is output from
       each table value line by replacing template
       values by table values.  After first template
       line all lines are kept as template line until
       the table starts.  Template "variables" are
       just text replacements.
       If the line is form: "$a" == "$b";
       it is not template line, but
       it can be forced template line be extra $ at the
       end of it, so: "$a" == "$b"; $ 
       
    3) Normal code                                       (NC)
       This is normal Java code after first table ends.
       Normal code is output immediately when it is hit.
       Normal code ends to first template line.
       
    4) Table heading                                     (TH)
       This is the first line after template lines 
       where there is at least one column separator 
         " | "
       or | as a first or last char in the line 
       (after removing * and trim)  
       There could be more columns
       than there is templates variables.  All template
       variable does not need to begin with $ (actually none), 
       but there is a big risk to change some unwanted 
       on that case.
       
    5) Table values.                                     (TV)
       These are lines with at least one column separator
         " | "
       or | as a first or last char in the line 
       (after removing * and trim)  
       If the cell value is ignore value
         "---"
       then all template sentences with that column header
       will be ignored.  
       
       Table values are substituted to corresponding template
       variables for each table line.  If there is sentences
       with $ after substitution then those sentences are 
       removed.
       
    6) Table separator (line)                            (LI)
         "-----"  (at least 5 "-" -signs)
       Table separator lines are comments. Actually it 
       can be anywhere in ComTest.  The whole line is 
       treated as a comment even ----- is in 
       the end of line
       
    7) Initialization separator                           (IZ)
         "====="  (at least 5 "=" -signs)
       After initialization separator the next table
       line or normal section causes start of new test case 
       and that starts with initialization section.
       The test cases are numbered by adding _n after
       original test case name.
       
    8) If Initialization separator is before first       (IZE)
       table heading, the whole table will be handled
       so that every line comes a new test case with
       initialization section.                  
       
    9) If there is normal lines or template lines
       after table, then that resets previous templates.
       
   10) All sentences with === is divided to leftSide and
       rightSide.  And then generated code
       assertEquals("explanation",rightSide,leftSide);    
       Note that for more complicated assert's one can write
       f.ex assertTrue("Should be less: #LINE#" , a < 3);
       
       Sentences with ~~~ or ~~ is handled as double
       comparison so they produce 
       assertEquals("explanation",rightSide,leftSide,#PRECISION);
       
       If the line has only one === or ~~ sentence
       then the ending ; may left out.
       
       Sentences with =R= or =~ is handled as regular expression
       comparison.    
           
       
   11) To write directly to Java class, introduce the
       test with name="testJAVA".  This turns Raw-mode on
       and on raw mode the lines are not written inside any 
       test case method.  In raw-mode there is no
       initialization section (IS), so on case of re-init
       no code is repeated.  
       To write JUnit annotations line .@Before the
       at sign  must be prefixed by any char to prevent
       JavaDoc going wrong.  The prefix char is removed.
   
   12) Lines that ends with                           
         #THROWS exceptionName
       is surrounded by "try ... fail() .. catch exceptionName e {}"
       so that line fails if the exception is not thrown.
       Note that the #THROWS works only line based.
       But if table line contains #THROWS then the
       template may generate more lines inside try catch.
       
       If #THROWS exeptionName is before any other line after pre-tag, 
       then the test is started by
         public void testN() throws exeptionName {
       
   13) Import is handled by "commands"
         #STATICIMPORT    - creates a line import static package.ClassName.*;
         #DYNAMICIMPORT   - creates a line import package.ClassName.*;
         #CLASSIMPORT     - creates a line import package.ClassName;
         #PACKAGEIMPORT   - creates a line import package.*;
         #NOIMPORT        - clears the automatic importing for JUnit
         #import impSentence; - adds the selected import sentence
       Import commands can be either in ComTest comments or in
       normal comments if there is only spaces before the command.
       If there is no import commands on the file or ComTest.ini files, then
       import package.ClassName; is inserted automatically
       
   14) The result directory and package can be changed be variables
         #DIRECTORY=dir   
         #PACKAGE=packageName
       in normal comments if there is only spaces before.
       If dir is relative, then it is appended to end of files directory.
       If packageName is .subPackageName then it is added to files
       packageName. 
       
   15) Variable sentences can be also in file
       ComTest.ini in same directory than the file to scan.
       In ini file the variables do not need to be in comments.
       Before # there is allowed only spaces.
       // is treated as a comment like in Java-file.  
       The ComTest.ini file is read first and the variables
       in the Java-file may override the values.                
          
   16) The symbols $, | , ---  and other "variables"
       can be changed by variable substitution lines     
          #COLUMNSEPARATOR=" | ";
          #COLUMNCHAR="|";
          #TEMPLATELINEMARKER="$";
          #DELETESENTENCEMARKER="---";
          #INITLINE="=====";
          #EVERYLINEINITS1="=====";
          #EVERYLINEINITS2="=== Every line inits ===";
          #EQUALSMARKER="===";
          #EQUALSMARKER2="=>";
          #ALMOSTMARKER1="~~~";
          #ALMOSTMARKER2="~~";
          #REGEXPMARKER1="=R=";
          #REGEXPMARKER2="=~";
          #TOLERANCE="0.000001";
          #THROWSMARKER="#THROWS";
          #IMPORTMARKER="#import";
          #PACKAGEMARKER="#PACKAGE=";
          #DIRECTORYMARKER="#DIRECTORY=";
       Each substitution must be in own line and
       = must be the next char after variable name.
       Variables are valid after substitution point until
       end of file or new change.  Every file starts with defaults.
       COLUMNCHAR variable is needed only if it is
       the first or last char on the line.  So mostly
       in one column tables.        
       Variable substitution can be in ComTest-comments or
       in normal comments if there is only spaces before the command.
   
     
 Example: Initialization section, template section and table 
          with two new initialization                           
   
 Counter cnt = new Counter(3);                            // IS 
 cnt.add($add);  cnt.getCount() === $count;               // TS  
 cnt.getSum() === $sum;                                   // TS
 cnt.getMax() === $max; cnt.getMin() === $min;            // TS
 
  ----------------------------------------------          // LI
     $add   |   $count   | $sum   | $max | $min           // TH
  ----------------------------------------------          // LI
     ---    |     0      |  0     |   0  |   0            // TV
      1     |     1      |  1     |   1  |   1            // TV
      2     |     2      |  1+2   |   2  |   1            // TV
      3     |     3      |  1+2+3 |   3  |   1            // TV
      4     |     3      |  6     |   3  |   1            // TV
  ==============================================          // IZ
      5     |     1      |  5     |   5  |   5            // TV 
      2     |     2      |  5+2   |   5  |   2            // TV
      3     |     3      |  5+2+3 |   5  |   2            // TV 
  ==============================================          // IZ
     -1     |     1      |  -1    |  -1  |  -1            // TV
      2     |     2      | -1+2   |   2  |  -1            // TV  
      9     |     3      | -1+2+9 |   9  |  -1            // TV
 
Below is a real life example from test with all sections and with many tables. For code generated see ComTestTest.testStringAdd()

Version:
29.9.2007 #STATICIMPORT #import comtest.Strings;
Author:
vesal
Example:
             
 // Example of many tables
   Strings list = new Strings();               // IS
   
   list.size() === 0;                          // IS
   list.add("$value"); list.size() === $size;  // TS
   list.get($i) === "$value";                  // TS
   
    $i   |  $value | $size                     // TH
   -------------------------                   // LI
     0   |  one    |  1                        // TV
     1   |  two    |  2                        // TV
     2   |  three  |  3                        // TV
     3   |  ---    |  3                        // TV

   list.get(3) === "three"; #THROWS IndexOutOfBoundsException // NC
        
   list.add("$value"); list.size() === $size;  // TS2
   list.add($b); // no output no variable $b   // --       
   
   === Every line inits ===
    $i   |  $value | $size                     // TH2
   -------------------------                   // LI
     0   |  one    |  1                        // TV
     1   |  two    |  1                        // TV 
     2   |  three  |  1                        // TV
     
 #COLUMNSEPARATOR=" , "; 
 #TEMPLATELINEMARKER="%";
   list.add("four"); list.size() === 1;        // NC 
   assertTrue("Strings: #LINE#",list.size()>0);// NC
   list.add("%value"); list.size() === %size;  // TS3
   assertTrue("Strings: #LINE#",list.size()>0);// TS3
   
    %i   ,  %value , %size                     // TH3
   -------------------------                   // LI
     0   ,  one    ,  2                        // TV
     1   ,  two    ,  3                        // TV
     2   ,  three  ,  4                        // TV
     
   if ( %i > 0 ) { list.get(%i) === "%value"; }// TS4
   
    %i   ,  %value                             // TH3
   -----------------                           // LI
     1   ,  one                                // TV
     2   ,  two                                // TV
     3   ,  three                              // TV
     4   ,  four   #THROWS IndexOutOfBoundsException 
    -1   ,  four   
     
 #COLUMNSEPARATOR=" | "; 
 #TEMPLATELINEMARKER="$";
 
,
  // Test double comparison and tolerance   
  double d1 = 0.1;                             // IS
  d1 ~~ 1.0/10;                                // IS
  #TOLERANCE=0.2;
  d1 ~~ 0;                                     // IS
  
,
  // Test regExp comparison
  "cat" =R= "c.*t"   
  "cat" =~  "c.*"   
  
,
 // Test raw mode and introduce an attribute and initializer 
 
 private Strings globalList;
 
 /.** *./    // This is the way to make comments inside comments 
 .@Before public void init() {// Run before ALL tests, not only those below
   globalList = new Strings();
   String st[] = {"one", "two", "three" };
   for (String s:st) globalList.add(s);
 }
 
,
             
   globalList.size() === 3;
   globalList.add("one");
 
,
             
   globalList.size() === 3;
   globalList.add("two");
 

Tips


Nested Class Summary
static class ComTest.ComTestScanner
          Class to do the file scanning and output for test class
static class ComTest.TestHelpper
          A class to help testing ComTest-functions.
 
Field Summary
private static java.lang.String ALMOSTMARKER1
           
private static java.lang.String ALMOSTMARKER2
           
private static java.lang.String CLASSIMPORT
           
private static java.lang.String COLUMNCHAR
           
private static java.lang.String COLUMNSEPARATOR
           
private static java.lang.String COMTESTBEGIN
           
private static java.lang.String COMTESTEND
           
private static java.lang.String COMTESTID
           
private static java.lang.String COMTESTIDOLD
           
private static java.lang.String COMTESTINI
           
private static java.lang.String DELETESENTENCEMARKER
           
private static java.lang.String DIRECTORYMARKER
           
private static java.lang.String DYNAMICIMPORT
           
private static java.lang.String EQUALSMARKER
           
private static java.lang.String EQUALSMARKER2
           
private static java.lang.String EVERYLINEINITS1
           
private static java.lang.String EVERYLINEINITS2
           
private static java.lang.String IMPORTMARKER
           
private static java.lang.String INITLINE
           
private static java.lang.String LINENUMBERMARKER
           
private static java.lang.String METHODINDEXMARKER
           
private static java.lang.String NOIMPORT
           
private static java.lang.String PACKAGEIMPORT
           
private static java.lang.String PACKAGEMARKER
           
private static java.lang.String REGEXPMARKER1
           
private static java.lang.String REGEXPMARKER2
           
private static java.lang.String SEPARATORLINE
           
private static java.lang.String STARTOFTEST
           
private static java.lang.String STATICIMPORT
           
private static java.lang.String TEMPLATELINEMARKER
           
private static java.lang.String TEST
           
private static java.lang.String THROWSMARKER
           
private static java.lang.String TOLERANCE
           
 
Constructor Summary
ComTest()
           
 
Method Summary
static void main(java.lang.String[] args)
           
static java.lang.String processFile(java.lang.String fileName)
          Process the file and make a unit test
static Strings splitToSentences(java.lang.String s)
          Split line to smaller tokens.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

TEST

private static final java.lang.String TEST
See Also:
Constant Field Values

SEPARATORLINE

private static final java.lang.String SEPARATORLINE
See Also:
Constant Field Values

LINENUMBERMARKER

private static final java.lang.String LINENUMBERMARKER
See Also:
Constant Field Values

METHODINDEXMARKER

private static final java.lang.String METHODINDEXMARKER
See Also:
Constant Field Values

STARTOFTEST

private static final java.lang.String STARTOFTEST
See Also:
Constant Field Values

COMTESTID

private static final java.lang.String COMTESTID
See Also:
Constant Field Values

COMTESTIDOLD

private static final java.lang.String COMTESTIDOLD
See Also:
Constant Field Values

COMTESTBEGIN

private static final java.lang.String COMTESTBEGIN
See Also:
Constant Field Values

COMTESTEND

private static final java.lang.String COMTESTEND
See Also:
Constant Field Values

STATICIMPORT

private static final java.lang.String STATICIMPORT
See Also:
Constant Field Values

DYNAMICIMPORT

private static final java.lang.String DYNAMICIMPORT
See Also:
Constant Field Values

CLASSIMPORT

private static final java.lang.String CLASSIMPORT
See Also:
Constant Field Values

PACKAGEIMPORT

private static final java.lang.String PACKAGEIMPORT
See Also:
Constant Field Values

NOIMPORT

private static final java.lang.String NOIMPORT
See Also:
Constant Field Values

COMTESTINI

private static final java.lang.String COMTESTINI
See Also:
Constant Field Values

COLUMNSEPARATOR

private static final java.lang.String COLUMNSEPARATOR
See Also:
Constant Field Values

COLUMNCHAR

private static final java.lang.String COLUMNCHAR
See Also:
Constant Field Values

TEMPLATELINEMARKER

private static final java.lang.String TEMPLATELINEMARKER
See Also:
Constant Field Values

DELETESENTENCEMARKER

private static final java.lang.String DELETESENTENCEMARKER
See Also:
Constant Field Values

INITLINE

private static final java.lang.String INITLINE
See Also:
Constant Field Values

EVERYLINEINITS1

private static final java.lang.String EVERYLINEINITS1
See Also:
Constant Field Values

EVERYLINEINITS2

private static final java.lang.String EVERYLINEINITS2
See Also:
Constant Field Values

EQUALSMARKER

private static final java.lang.String EQUALSMARKER
See Also:
Constant Field Values

EQUALSMARKER2

private static final java.lang.String EQUALSMARKER2
See Also:
Constant Field Values

ALMOSTMARKER1

private static final java.lang.String ALMOSTMARKER1
See Also:
Constant Field Values

ALMOSTMARKER2

private static final java.lang.String ALMOSTMARKER2
See Also:
Constant Field Values

REGEXPMARKER1

private static final java.lang.String REGEXPMARKER1
See Also:
Constant Field Values

REGEXPMARKER2

private static final java.lang.String REGEXPMARKER2
See Also:
Constant Field Values

TOLERANCE

private static final java.lang.String TOLERANCE
See Also:
Constant Field Values

THROWSMARKER

private static final java.lang.String THROWSMARKER
See Also:
Constant Field Values

IMPORTMARKER

private static final java.lang.String IMPORTMARKER
See Also:
Constant Field Values

PACKAGEMARKER

private static final java.lang.String PACKAGEMARKER
See Also:
Constant Field Values

DIRECTORYMARKER

private static final java.lang.String DIRECTORYMARKER
See Also:
Constant Field Values
Constructor Detail

ComTest

public ComTest()
Method Detail

splitToSentences

public static Strings splitToSentences(java.lang.String s)
Split line to smaller tokens. Line is divided from ;, { or }. The splitter chars are returned as own one char sentences.

Parameters:
s - line to split
Returns:
line that is split to smaller sentences.
Example:
   Strings sns = splitToSentences("a === 5;");
   sns.size() === 2; 
   sns.get(0) === "a === 5"; sns.get(1) === "; "; 
   sns.toString("|") === "a === 5|; "; 

   sns = splitToSentences("a === 5; b === 3;");
   sns.size() === 4; 
   sns.toString("|") === "a === 5|; | b === 3|; "; 

   sns = splitToSentences("if ( a < 3 ) { a === 5; } else b === 3;");
   sns.size() === 8; 
   sns.toString("|") === "if ( a < 3 ) |{ | a === 5|; |} |else | b === 3|; "; 

   sns = splitToSentences("if ( a < 3 ) { a === 5; } else { b === 3; }");
   sns.size() === 10;
   sns.toString("|") === "if ( a < 3 ) |{ | a === 5|; |} |else |{ | b === 3|; | }";
   
   sns = splitToSentences("get(request,new String[]{\"str\",\"id\"},13,true) === 123;"); 
   sns.size() === 2;
   sns.toString("|") === "get(request,new String[]{\"str\",\"id\"},13,true) === 123|; ";
 

processFile

public static java.lang.String processFile(java.lang.String fileName)
Process the file and make a unit test

Parameters:
fileName - the name of the file to process
Returns:
handled filename in success, null otherwise

main

public static void main(java.lang.String[] args)
Parameters:
args - name of files to process