Coverage Report - org.jbehave.core.reporters.PrintStreamOutput
 
Classes in this File Line Coverage Branch Coverage Complexity
PrintStreamOutput
100%
99/99
86%
19/22
1.586
PrintStreamOutput$1
100%
6/6
80%
4/5
1.586
PrintStreamOutput$2
100%
1/1
N/A
1.586
PrintStreamOutput$Format
100%
1/1
N/A
1.586
 
 1  
 package org.jbehave.core.reporters;
 2  
 
 3  
 import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
 4  
 import static org.apache.commons.lang.StringEscapeUtils.escapeXml;
 5  
 import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_END;
 6  
 import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_NEWLINE;
 7  
 import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_START;
 8  
 
 9  
 import java.io.ByteArrayOutputStream;
 10  
 import java.io.PrintStream;
 11  
 import java.text.MessageFormat;
 12  
 import java.util.Arrays;
 13  
 import java.util.List;
 14  
 import java.util.Locale;
 15  
 import java.util.Map;
 16  
 import java.util.Properties;
 17  
 
 18  
 import org.apache.commons.collections.CollectionUtils;
 19  
 import org.apache.commons.collections.Transformer;
 20  
 import org.apache.commons.lang.ArrayUtils;
 21  
 import org.apache.commons.lang.builder.ToStringBuilder;
 22  
 import org.apache.commons.lang.builder.ToStringStyle;
 23  
 import org.jbehave.core.configuration.Keywords;
 24  
 import org.jbehave.core.model.ExamplesTable;
 25  
 import org.jbehave.core.model.Narrative;
 26  
 import org.jbehave.core.model.OutcomesTable;
 27  
 import org.jbehave.core.model.Story;
 28  
 import org.jbehave.core.model.OutcomesTable.Outcome;
 29  
 
 30  
 /**
 31  
  * <p>
 32  
  * Abstract story reporter that outputs to a PrintStream.
 33  
  * </p>
 34  
  * <p>
 35  
  * The output of the reported event is configurable via:
 36  
  * <ul>
 37  
  * <li>custom output patterns, providing only the patterns that differ from
 38  
  * default</li>
 39  
  * <li>keywords localised for different languages, providing the i18n Locale</li>
 40  
  * <li>flag to report failure trace</li>
 41  
  * </ul>
 42  
  * </p>
 43  
  * <p>
 44  
  * Let's look at example of providing custom output patterns, e.g. for the
 45  
  * failed event. <br/>
 46  
  * we'd need to provide the custom pattern, say we want to have something like
 47  
  * "(step being executed) <<< FAILED", keyed on the method name:
 48  
  * 
 49  
  * <pre>
 50  
  * Properties patterns = new Properties();
 51  
  * patterns.setProperty(&quot;failed&quot;, &quot;{0} &lt;&lt;&lt; {1}&quot;);
 52  
  * </pre>
 53  
  * 
 54  
  * The pattern is by default processed and formatted by the
 55  
  * {@link MessageFormat}. Both the {@link #format(String key, String defaultPattern, Object... args)} and
 56  
  * {@link #lookupPattern(String key, String defaultPattern)} methods are override-able and a different formatter
 57  
  * or pattern lookup can be used by subclasses.
 58  
  * </p>
 59  
  * <p>
 60  
  * If the keyword "FAILED" (or any other keyword used by the reporter) needs to
 61  
  * be expressed in a different language, all we need to do is to provide an
 62  
  * instance of {@link org.jbehave.core.i18n.LocalizedKeywords} using the appropriate {@link Locale}, e.g.
 63  
  * 
 64  
  * <pre>
 65  
  * Keywords keywords = new LocalizedKeywords(new Locale(&quot;it&quot;));
 66  
  * </pre>
 67  
  * 
 68  
  * </p>
 69  
  */
 70  
 public abstract class PrintStreamOutput implements StoryReporter {
 71  
 
 72  
     private static final String EMPTY = "";
 73  
 
 74  5
     public enum Format { TXT, HTML, XML }
 75  
     
 76  
     private final Format format;    
 77  
     private final PrintStream output;
 78  
     private final Properties outputPatterns;
 79  
     private final Keywords keywords;
 80  
     private boolean reportFailureTrace;
 81  
     private Throwable cause;
 82  
     
 83  
     protected PrintStreamOutput(Format format, PrintStream output, Properties outputPatterns,
 84  414
             Keywords keywords, boolean reportFailureTrace) {
 85  414
         this.format = format;
 86  414
         this.output = output;
 87  414
         this.outputPatterns = outputPatterns;
 88  414
         this.keywords = keywords;
 89  414
         this.reportFailureTrace = reportFailureTrace;   
 90  414
     }
 91  
 
 92  
     public void successful(String step) {
 93  44
         print(format("successful", "{0}\n", step));
 94  44
     }
 95  
 
 96  
     public void ignorable(String step) {
 97  12
         print(format("ignorable", "{0}\n", step));
 98  12
     }
 99  
 
 100  
     public void pending(String step) {
 101  16
         print(format("pending", "{0} ({1})\n", step, keywords.pending()));
 102  16
     }
 103  
 
 104  
     public void notPerformed(String step) {
 105  16
         print(format("notPerformed", "{0} ({1})\n", step, keywords.notPerformed()));
 106  16
     }
 107  
 
 108  
     public void failed(String step, Throwable cause) {
 109  17
         this.cause = cause;
 110  17
         print(format("failed", "{0} ({1})\n({2})\n", step, keywords.failed(), cause));        
 111  17
     }
 112  
 
 113  
     public void failedOutcomes(String step, OutcomesTable table) {
 114  12
             failed(step, table.failureCause());
 115  12
         print(table);
 116  12
     }
 117  
     
 118  
         private void print(OutcomesTable table) {
 119  12
                 print(format("outcomesTableStart", "\n"));
 120  12
         List<Outcome<?>> rows = table.getOutcomes();
 121  12
         print(format("outcomesTableHeadStart", "|"));
 122  
         //TODO i18n outcome fields
 123  12
         for (String field : table.getOutcomeFields()) {
 124  48
             print(format("outcomesTableHeadCell", "{0}|", field));
 125  
         }
 126  12
         print(format("outcomesTableHeadEnd", "\n"));
 127  12
         print(format("outcomesTableBodyStart", EMPTY));
 128  12
         for (Outcome<?> outcome : rows) {
 129  12
             print(format("outcomesTableRowStart", "|", outcome.isVerified()?"verified":"notVerified"));
 130  12
             print(format("outcomesTableCell", "{0}|", outcome.getDescription()));
 131  12
             print(format("outcomesTableCell", "{0}|", outcome.getValue()));
 132  12
             print(format("outcomesTableCell", "{0}|", outcome.getMatcher()));
 133  12
             print(format("outcomesTableCell", "{0}|", outcome.isVerified()));
 134  12
             print(format("outcomesTableRowEnd", "\n"));
 135  
         }
 136  12
         print(format("outcomesTableBodyEnd", "\n"));
 137  12
         print(format("outcomesTableEnd", "\n"));
 138  12
         }
 139  
 
 140  
     public void beforeStory(Story story, boolean givenStory) {
 141  12
         print(format("beforeStory", "{0}\n({1})\n", story.getDescription().asString(), story.getPath()));
 142  12
         if (!story.getNarrative().isEmpty()) {
 143  12
             Narrative narrative = story.getNarrative();
 144  12
             print(format("narrative", "{0}\n{1} {2}\n{3} {4}\n{5} {6}\n", keywords.narrative(), keywords.inOrderTo(),
 145  
                     narrative.inOrderTo(), keywords.asA(), narrative.asA(), keywords.iWantTo(), narrative.iWantTo()));
 146  
         }
 147  12
     }
 148  
 
 149  
     public void afterStory(boolean givenStory) {
 150  12
         print(format("afterStory", "\n"));
 151  12
     }
 152  
 
 153  
     public void givenStories(List<String> storyPaths) {
 154  12
         print(format("givenStories", "{0} {1}\n", keywords.givenStories(), storyPaths));
 155  12
     }
 156  
 
 157  
     public void beforeScenario(String title) {
 158  14
         cause = null;
 159  14
         print(format("beforeScenario", "{0} {1}\n", keywords.scenario(), title));
 160  14
     }
 161  
 
 162  
     public void afterScenario() {
 163  14
         if (cause != null && reportFailureTrace) {
 164  3
             print(format("afterScenarioWithFailure", "\n{0}\n", stackTrace(cause)));
 165  
         } else {
 166  11
             print(format("afterScenario", "\n"));
 167  
         }
 168  14
     }
 169  
 
 170  
     private String stackTrace(Throwable cause) {
 171  3
         ByteArrayOutputStream out = new ByteArrayOutputStream();        
 172  3
         cause.printStackTrace(new PrintStream(out));
 173  3
         return out.toString();
 174  
     }
 175  
 
 176  
     public void beforeExamples(List<String> steps, ExamplesTable table) {
 177  12
         print(format("beforeExamples", "{0}\n", keywords.examplesTable()));
 178  12
         for (String step : steps) {
 179  24
             print(format("examplesStep", "{0}\n", step));
 180  
         }
 181  12
         print(table);
 182  12
     }
 183  
 
 184  
         private void print(ExamplesTable table) {
 185  12
                 print(format("examplesTableStart", "\n"));
 186  12
         List<Map<String, String>> rows = table.getRows();
 187  12
         List<String> headers = table.getHeaders();
 188  12
         print(format("examplesTableHeadStart", "|"));
 189  12
         for (String header : headers) {
 190  24
             print(format("examplesTableHeadCell", "{0}|", header));
 191  
         }
 192  12
         print(format("examplesTableHeadEnd", "\n"));
 193  12
         print(format("examplesTableBodyStart", EMPTY));
 194  12
         for (Map<String, String> row : rows) {
 195  24
             print(format("examplesTableRowStart", "|"));
 196  24
             for (String header : headers) {
 197  48
                 print(format("examplesTableCell", "{0}|", row.get(header)));
 198  
             }
 199  24
             print(format("examplesTableRowEnd", "\n"));
 200  
         }
 201  12
         print(format("examplesTableBodyEnd", "\n"));
 202  12
         print(format("examplesTableEnd", "\n"));
 203  12
         }
 204  
 
 205  
     public void example(Map<String, String> tableRow) {
 206  24
         print(format("example", "\n{0} {1}\n", keywords.examplesTableRow(), tableRow));
 207  24
     }
 208  
 
 209  
     public void afterExamples() {
 210  12
         print(format("afterExamples", "\n"));
 211  12
     }
 212  
 
 213  
         public void dryRun() {
 214  12
                 print(format("dryRun", "{0}\n", keywords.dryRun()));
 215  12
         }
 216  
 
 217  
     /**
 218  
      * Formats event output by key, usually equal to the method name.
 219  
      * 
 220  
      * @param key the event key
 221  
      * @param defaultPattern the default pattern to return if a custom pattern
 222  
      *            is not found
 223  
      * @param args the args used to format output
 224  
      * @return A formatted event output
 225  
      */
 226  
     protected String format(String key, String defaultPattern, Object... args) {
 227  4543
         return MessageFormat.format(lookupPattern(key, escape(defaultPattern)), escapeAll(args));
 228  
     }
 229  
 
 230  
     private String escape(String defaultPattern) {
 231  4543
         return (String) escapeAll(defaultPattern)[0];
 232  
     }
 233  
 
 234  
     private Object[] escapeAll(Object... args) {
 235  9086
         return escape(format, args);
 236  
     }
 237  
 
 238  
     /**
 239  
      * Escapes args' string values according to format
 240  
      * 
 241  
      * @param format the Format used by the PrintStream
 242  
      * @param args the array of args to escape
 243  
      * @return The cloned and escaped array of args
 244  
      */
 245  
     protected Object[] escape(final Format format, Object... args) {
 246  
         // Transformer that escapes HTML and XML strings
 247  9086
         Transformer escapingTransformer = new Transformer( ) {
 248  
             public Object transform(Object object) {
 249  5153
                 switch ( format ){
 250  1644
                     case HTML: return escapeHtml(asString(object));
 251  411
                     case XML: return escapeXml(asString(object));
 252  3098
                     default: return object;
 253  
                 }
 254  
             }
 255  
 
 256  
             private String asString(Object object) {
 257  2055
                 return  ( object != null ? object.toString() : EMPTY );
 258  
             }
 259  
         };
 260  9086
         List<?> list = Arrays.asList( ArrayUtils.clone( args ) );
 261  9086
         CollectionUtils.transform( list, escapingTransformer );
 262  9086
         return list.toArray();
 263  
     }
 264  
 
 265  
     /**
 266  
      * Looks up the format pattern for the event output by key, conventionally
 267  
      * equal to the method name. The pattern is used by the
 268  
      * {#format(String,String,Object...)} method and by default is formatted
 269  
      * using the {@link MessageFormat#format(String, Object...)} method. If no pattern is found
 270  
      * for key or needs to be overridden, the default pattern should be
 271  
      * returned.
 272  
      * 
 273  
      * @param key the format pattern key
 274  
      * @param defaultPattern the default pattern if no pattern is
 275  
      * @return The format patter for the given key
 276  
      */
 277  
     protected String lookupPattern(String key, String defaultPattern) {
 278  4543
         if (outputPatterns.containsKey(key)) {
 279  2589
             return outputPatterns.getProperty(key);
 280  
         }
 281  1954
         return defaultPattern;
 282  
     }
 283  
 
 284  
     public PrintStreamOutput doReportFailureTrace(boolean reportFailureTrace){
 285  13
             this.reportFailureTrace = reportFailureTrace;
 286  13
             return this;
 287  
     }
 288  
     
 289  
     /**
 290  
      * Prints text to output stream, replacing parameter start and end placeholders
 291  
      * 
 292  
      * @param text the String to print
 293  
      */
 294  
     protected void print(String text) {
 295  649
         output.print(text.replace(format(PARAMETER_VALUE_START, PARAMETER_VALUE_START), format("parameterValueStart", EMPTY))
 296  
                          .replace(format(PARAMETER_VALUE_END, PARAMETER_VALUE_END), format("parameterValueEnd", EMPTY))
 297  
                          .replace(format(PARAMETER_VALUE_NEWLINE, PARAMETER_VALUE_NEWLINE), format("parameterValueNewline", "\n")));
 298  649
     }
 299  
     
 300  
         @Override
 301  
         public String toString() {
 302  1
                 return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
 303  
         }
 304  
 
 305  
 }