Coverage Report - org.jbehave.core.reporters.PrintStreamOutput
 
Classes in this File Line Coverage Branch Coverage Complexity
PrintStreamOutput
86%
160/185
71%
46/64
1.87
PrintStreamOutput$1
100%
6/6
80%
4/5
1.87
PrintStreamOutput$2
100%
1/1
N/A
1.87
PrintStreamOutput$Format
100%
2/2
N/A
1.87
 
 1  
 package org.jbehave.core.reporters;
 2  
 
 3  
 import java.io.ByteArrayOutputStream;
 4  
 import java.io.OutputStream;
 5  
 import java.io.PrintStream;
 6  
 import java.text.MessageFormat;
 7  
 import java.text.SimpleDateFormat;
 8  
 import java.util.Arrays;
 9  
 import java.util.Date;
 10  
 import java.util.List;
 11  
 import java.util.Locale;
 12  
 import java.util.Map;
 13  
 import java.util.Properties;
 14  
 
 15  
 import org.apache.commons.collections.CollectionUtils;
 16  
 import org.apache.commons.collections.Transformer;
 17  
 import org.apache.commons.lang.ArrayUtils;
 18  
 import org.apache.commons.lang.StringUtils;
 19  
 import org.apache.commons.lang.builder.ToStringBuilder;
 20  
 import org.apache.commons.lang.builder.ToStringStyle;
 21  
 import org.jbehave.core.configuration.Keywords;
 22  
 import org.jbehave.core.failures.KnownFailure;
 23  
 import org.jbehave.core.failures.UUIDExceptionWrapper;
 24  
 import org.jbehave.core.model.ExamplesTable;
 25  
 import org.jbehave.core.model.GivenStories;
 26  
 import org.jbehave.core.model.GivenStory;
 27  
 import org.jbehave.core.model.Lifecycle;
 28  
 import org.jbehave.core.model.Meta;
 29  
 import org.jbehave.core.model.Narrative;
 30  
 import org.jbehave.core.model.OutcomesTable;
 31  
 import org.jbehave.core.model.OutcomesTable.Outcome;
 32  
 import org.jbehave.core.model.Scenario;
 33  
 import org.jbehave.core.model.Story;
 34  
 import org.jbehave.core.model.StoryDuration;
 35  
 
 36  
 import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
 37  
 import static org.apache.commons.lang.StringEscapeUtils.escapeXml;
 38  
 import static org.apache.commons.lang.StringUtils.substringBetween;
 39  
 import static org.jbehave.core.steps.StepCreator.PARAMETER_TABLE_END;
 40  
 import static org.jbehave.core.steps.StepCreator.PARAMETER_TABLE_START;
 41  
 import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_END;
 42  
 import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_NEWLINE;
 43  
 import static org.jbehave.core.steps.StepCreator.PARAMETER_VALUE_START;
 44  
 
 45  
 /**
 46  
  * <p>
 47  
  * Abstract story reporter that outputs to a PrintStream.
 48  
  * </p>
 49  
  * <p>
 50  
  * The output of the reported event is configurable via:
 51  
  * <ul>
 52  
  * <li>custom output patterns, providing only the patterns that differ from
 53  
  * default</li>
 54  
  * <li>keywords localised for different languages, providing the i18n Locale</li>
 55  
  * <li>flag to report failure trace</li>
 56  
  * </ul>
 57  
  * </p>
 58  
  * <p>
 59  
  * Let's look at example of providing custom output patterns, e.g. for the
 60  
  * failed event. <br/>
 61  
  * we'd need to provide the custom pattern, say we want to have something like
 62  
  * "(step being executed) <<< FAILED", keyed on the method name:
 63  
  * 
 64  
  * <pre>
 65  
  * Properties patterns = new Properties();
 66  
  * patterns.setProperty(&quot;failed&quot;, &quot;{0} &lt;&lt;&lt; {1}&quot;);
 67  
  * </pre>
 68  
  * 
 69  
  * The pattern is by default processed and formatted by the
 70  
  * {@link MessageFormat}. Both the
 71  
  * {@link #format(String key, String defaultPattern, Object... args)} and
 72  
  * {@link #lookupPattern(String key, String defaultPattern)} methods are
 73  
  * override-able and a different formatter or pattern lookup can be used by
 74  
  * subclasses.
 75  
  * </p>
 76  
  * <p>
 77  
  * If the keyword "FAILED" (or any other keyword used by the reporter) needs to
 78  
  * be expressed in a different language, all we need to do is to provide an
 79  
  * instance of {@link org.jbehave.core.i18n.LocalizedKeywords} using the
 80  
  * appropriate {@link Locale}, e.g.
 81  
  * 
 82  
  * <pre>
 83  
  * Keywords keywords = new LocalizedKeywords(new Locale(&quot;it&quot;));
 84  
  * </pre>
 85  
  * 
 86  
  * </p>
 87  
  */
 88  
 public abstract class PrintStreamOutput implements StoryReporter {
 89  
 
 90  
     private static final String EMPTY = "";
 91  
 
 92  5
     public enum Format {
 93  1
         TXT, HTML, XML
 94  
     }
 95  
 
 96  
     private final Format format;
 97  
     private final PrintStream output;
 98  
     private final Properties outputPatterns;
 99  
     private final Keywords keywords;
 100  343
     private ThreadLocal<Boolean> reportFailureTrace = new ThreadLocal<Boolean>();
 101  343
     private ThreadLocal<Boolean> compressFailureTrace = new ThreadLocal<Boolean>();
 102  343
     private ThreadLocal<Throwable> cause = new ThreadLocal<Throwable>();
 103  
 
 104  
     protected PrintStreamOutput(Format format, PrintStream output, Properties outputPatterns, Keywords keywords,
 105  343
             boolean reportFailureTrace, boolean compressFailureTrace) {
 106  343
         this.format = format;
 107  343
         this.output = output;
 108  343
         this.outputPatterns = outputPatterns;
 109  343
         this.keywords = keywords;
 110  343
         doReportFailureTrace(reportFailureTrace);
 111  343
         doCompressFailureTrace(compressFailureTrace);
 112  343
     }
 113  
 
 114  
     public void beforeStep(String step) {
 115  5
     }
 116  
 
 117  
     public void successful(String step) {
 118  140
         print(format("successful", "{0}\n", step));
 119  140
     }
 120  
 
 121  
     public void ignorable(String step) {
 122  12
         print(format("ignorable", "{0}\n", step));
 123  12
     }
 124  
 
 125  
     public void pending(String step) {
 126  28
         print(format("pending", "{0} ({1})\n", step, keywords.pending()));
 127  28
     }
 128  
 
 129  
     public void notPerformed(String step) {
 130  16
         print(format("notPerformed", "{0} ({1})\n", step, keywords.notPerformed()));
 131  16
     }
 132  
 
 133  
     public void failed(String step, Throwable storyFailure) {
 134  
         // storyFailure be used if a subclass has rewritten the "failed" pattern
 135  
         // to have a {3} as WebDriverHtmlOutput (jbehave-web) does.
 136  25
         if (storyFailure instanceof UUIDExceptionWrapper) {
 137  25
             this.cause.set(storyFailure.getCause());
 138  25
             print(format("failed", "{0} ({1})\n({2})\n", step, keywords.failed(), storyFailure.getCause(),
 139  
                     ((UUIDExceptionWrapper) storyFailure).getUUID()));
 140  
         } else {
 141  0
             throw new ClassCastException(storyFailure + " should be an instance of UUIDExceptionWrapper");
 142  
         }
 143  25
     }
 144  
 
 145  
     public void failedOutcomes(String step, OutcomesTable table) {
 146  13
         failed(step, table.failureCause());
 147  13
         print(table);
 148  13
     }
 149  
 
 150  
     private void print(OutcomesTable table) {
 151  13
         print(format("outcomesTableStart", "\n"));
 152  13
         List<Outcome<?>> rows = table.getOutcomes();
 153  13
         print(format("outcomesTableHeadStart", "|"));
 154  13
         for (String field : table.getOutcomeFields()) {
 155  52
             print(format("outcomesTableHeadCell", "{0}|", field));
 156  52
         }
 157  13
         print(format("outcomesTableHeadEnd", "\n"));
 158  13
         print(format("outcomesTableBodyStart", EMPTY));
 159  13
         for (Outcome<?> outcome : rows) {
 160  25
             print(format("outcomesTableRowStart", "|", outcome.isVerified() ? "verified" : "notVerified"));
 161  25
             print(format("outcomesTableCell", "{0}|", outcome.getDescription()));
 162  25
             print(format("outcomesTableCell", "{0}|", renderOutcomeValue(outcome.getValue(), table.getDateFormat())));
 163  25
             print(format("outcomesTableCell", "{0}|", outcome.getMatcher()));
 164  25
             print(format("outcomesTableCell", "{0}|", (outcome.isVerified() ? keywords.yes() : keywords.no())));
 165  25
             print(format("outcomesTableRowEnd", "\n"));
 166  25
         }
 167  13
         print(format("outcomesTableBodyEnd", "\n"));
 168  13
         print(format("outcomesTableEnd", "\n"));
 169  13
     }
 170  
 
 171  
     private Object renderOutcomeValue(Object value, String dateFormat) {
 172  25
         if (value instanceof Date) {
 173  13
             return new SimpleDateFormat(dateFormat).format(value);
 174  
         } else {
 175  12
             return value;
 176  
         }
 177  
     }
 178  
 
 179  
     public void storyNotAllowed(Story story, String filter) {
 180  0
         print(format("filter", "{0}\n", filter));
 181  0
     }
 182  
 
 183  
     public void storyCancelled(Story story, StoryDuration storyDuration) {
 184  17
         print(format("storyCancelled", "{0}: {1} ({2} s)\n", keywords.storyCancelled(), keywords.duration(),
 185  
                 storyDuration.getDurationInSecs()));
 186  17
     }
 187  
 
 188  
     public void beforeStory(Story story, boolean givenStory) {
 189  32
         print(format("beforeStory", "{0}\n({1})\n", story.getDescription().asString(), story.getPath()));
 190  32
         if (!story.getMeta().isEmpty()) {
 191  15
             Meta meta = story.getMeta();
 192  15
             print(meta);
 193  
         }
 194  32
     }
 195  
 
 196  
     public void narrative(Narrative narrative) {
 197  20
         if (!narrative.isEmpty()) {
 198  12
             if (!narrative.isAlternative()) {
 199  12
                 print(format("narrative", "{0}\n{1} {2}\n{3} {4}\n{5} {6}\n", keywords.narrative(),
 200  
                         keywords.inOrderTo(), narrative.inOrderTo(), keywords.asA(), narrative.asA(),
 201  
                         keywords.iWantTo(), narrative.iWantTo()));
 202  
             } else {
 203  0
                 print(format("narrative", "{0}\n{1} {2}\n{3} {4}\n{5} {6}\n", keywords.narrative(), keywords.asA(),
 204  
                         narrative.asA(), keywords.iWantTo(), narrative.iWantTo(), keywords.soThat(), narrative.soThat()));
 205  
             }
 206  
         }
 207  20
     }
 208  
 
 209  
     public void lifecyle(Lifecycle lifecycle) {
 210  8
         if (!lifecycle.isEmpty()) {
 211  0
             print(format("lifecycleStart", "{0}\n", keywords.lifecycle()));
 212  0
             if (!lifecycle.getBeforeSteps().isEmpty()) {
 213  0
                 print(format("lifecycleBeforeStart", "{0}\n", keywords.before()));
 214  0
                 print(lifecycle.getBeforeSteps());
 215  0
                 print(format("lifecycleBeforeEnd", ""));
 216  
             }
 217  0
             if (!lifecycle.getAfterSteps().isEmpty()) {
 218  0
                 print(format("lifecycleAfterStart", "{0}\n", keywords.after()));
 219  0
                 print(lifecycle.getAfterSteps());
 220  0
                 print(format("lifecycleAfterEnd", ""));
 221  
             }
 222  0
             print(format("lifecycleEnd", "\n"));
 223  
         }
 224  8
     }
 225  
 
 226  
     private void print(List<String> steps) {
 227  0
         for (String step : steps) {
 228  0
             print(format("lifecycleStep", "{0}\n", step));
 229  0
         }
 230  0
     }
 231  
 
 232  
     private void print(Meta meta) {
 233  15
         print(format("metaStart", "{0}\n", keywords.meta()));
 234  15
         for (String name : meta.getPropertyNames()) {
 235  30
             print(format("metaProperty", "{0}{1} {2}", keywords.metaProperty(), name, meta.getProperty(name)));
 236  30
         }
 237  15
         print(format("metaEnd", "\n"));
 238  15
     }
 239  
 
 240  
     public void afterStory(boolean givenStory) {
 241  34
         print(format("afterStory", "\n"));
 242  
         // take care not to close System.out
 243  
         // which is used for ConsoleOutput
 244  34
         if (!givenStory && output != System.out) {
 245  30
             output.close();
 246  
         }
 247  34
     }
 248  
 
 249  
     public void givenStories(GivenStories givenStories) {
 250  12
         print(format("givenStoriesStart", "{0}\n", keywords.givenStories()));
 251  12
         for (GivenStory givenStory : givenStories.getStories()) {
 252  24
             print(format("givenStory", "{0} {1}\n", givenStory.asString(),
 253  
                     (givenStory.hasAnchor() ? givenStory.getParameters() : "")));
 254  24
         }
 255  12
         print(format("givenStoriesEnd", "\n"));
 256  12
     }
 257  
 
 258  
     public void givenStories(List<String> storyPaths) {
 259  12
         givenStories(new GivenStories(StringUtils.join(storyPaths, ",")));
 260  12
     }
 261  
 
 262  
     public void scenarioNotAllowed(Scenario scenario, String filter) {
 263  3
         print(format("filter", "{0}\n", filter));
 264  3
     }
 265  
 
 266  
     public void beforeScenario(String title) {
 267  37
         cause.set(null);
 268  37
         print(format("beforeScenario", "{0} {1}\n", keywords.scenario(), title));
 269  37
     }
 270  
 
 271  
     public void scenarioMeta(Meta meta) {
 272  8
         if (!meta.isEmpty()) {
 273  0
             print(meta);
 274  
         }
 275  8
     }
 276  
 
 277  
     public void afterScenario() {
 278  41
         if (cause.get() != null && !(cause.get() instanceof KnownFailure) && reportFailureTrace() ) {
 279  4
             print(format("afterScenarioWithFailure", "\n{0}\n",
 280  
                     new StackTraceFormatter(compressFailureTrace()).stackTrace(cause.get())));
 281  
         } else {
 282  37
             print(format("afterScenario", "\n"));
 283  
         }
 284  41
     }
 285  
 
 286  
     public void beforeExamples(List<String> steps, ExamplesTable table) {
 287  12
         print(format("beforeExamples", "{0}\n", keywords.examplesTable()));
 288  12
         for (String step : steps) {
 289  24
             print(format("examplesStep", "{0}\n", step));
 290  24
         }
 291  12
         print(formatTable(table));
 292  12
     }
 293  
 
 294  
     public void example(Map<String, String> tableRow) {
 295  24
         print(format("example", "\n{0} {1}\n", keywords.examplesTableRow(), tableRow));
 296  24
     }
 297  
 
 298  
     public void afterExamples() {
 299  12
         print(format("afterExamples", "\n"));
 300  12
     }
 301  
 
 302  
     public void dryRun() {
 303  12
         print(format("dryRun", "{0}\n", keywords.dryRun()));
 304  12
     }
 305  
 
 306  
     public void pendingMethods(List<String> methods) {
 307  12
         for (String method : methods) {
 308  24
             print(format("pendingMethod", "{0}\n", method));
 309  24
         }
 310  12
     }
 311  
 
 312  
     public void restarted(String step, Throwable cause) {
 313  12
         print(format("restarted", "{0} {1}\n", step, cause.getMessage()));
 314  12
     }
 315  
 
 316  
     /**
 317  
      * Formats event output by key, usually equal to the method name.
 318  
      * 
 319  
      * @param key the event key
 320  
      * @param defaultPattern the default pattern to return if a custom pattern
 321  
      *            is not found
 322  
      * @param args the args used to format output
 323  
      * @return A formatted event output
 324  
      */
 325  
     protected String format(String key, String defaultPattern, Object... args) {
 326  8441
         String escape = escape(defaultPattern);
 327  8441
         String s = lookupPattern(key, escape);
 328  8441
         Object[] objects = escapeAll(args);
 329  8441
         return MessageFormat.format(s, objects);
 330  
     }
 331  
 
 332  
     protected String formatTable(ExamplesTable table) {
 333  12
         OutputStream formatted = new ByteArrayOutputStream();
 334  12
         PrintStream out = new PrintStream(formatted);
 335  12
         out.print(format("examplesTableStart", "\n"));
 336  12
         List<Map<String, String>> rows = table.getRows();
 337  12
         List<String> headers = table.getHeaders();
 338  12
         out.print(format("examplesTableHeadStart", "|"));
 339  12
         for (String header : headers) {
 340  24
             out.print(format("examplesTableHeadCell", "{0}|", header));
 341  24
         }
 342  12
         out.print(format("examplesTableHeadEnd", "\n"));
 343  12
         out.print(format("examplesTableBodyStart", EMPTY));
 344  12
         for (Map<String, String> row : rows) {
 345  24
             out.print(format("examplesTableRowStart", "|"));
 346  24
             for (String header : headers) {
 347  48
                 out.print(format("examplesTableCell", "{0}|", row.get(header)));
 348  48
             }
 349  24
             out.print(format("examplesTableRowEnd", "\n"));
 350  24
         }
 351  12
         out.print(format("examplesTableBodyEnd", ""));
 352  12
         out.print(format("examplesTableEnd", ""));
 353  12
         return formatted.toString();
 354  
     }
 355  
 
 356  
     private String escape(String defaultPattern) {
 357  8441
         return (String) escapeAll(defaultPattern)[0];
 358  
     }
 359  
 
 360  
     private Object[] escapeAll(Object... args) {
 361  16882
         return escape(format, args);
 362  
     }
 363  
 
 364  
     /**
 365  
      * Escapes args' string values according to format
 366  
      * 
 367  
      * @param format the Format used by the PrintStream
 368  
      * @param args the array of args to escape
 369  
      * @return The cloned and escaped array of args
 370  
      */
 371  
     protected Object[] escape(final Format format, Object... args) {
 372  
         // Transformer that escapes HTML and XML strings
 373  16882
         Transformer escapingTransformer = new Transformer() {
 374  
             public Object transform(Object object) {
 375  9627
                 switch (format) {
 376  
                 case HTML:
 377  2966
                     return escapeHtml(asString(object));
 378  
                 case XML:
 379  1086
                     return escapeXml(asString(object));
 380  
                 default:
 381  5575
                     return object;
 382  
                 }
 383  
             }
 384  
 
 385  
             private String asString(Object object) {
 386  4052
                 return (object != null ? object.toString() : EMPTY);
 387  
             }
 388  
         };
 389  16882
         List<?> list = Arrays.asList(ArrayUtils.clone(args));
 390  16882
         CollectionUtils.transform(list, escapingTransformer);
 391  16882
         return list.toArray();
 392  
     }
 393  
 
 394  
     /**
 395  
      * Looks up the format pattern for the event output by key, conventionally
 396  
      * equal to the method name. The pattern is used by the
 397  
      * {#format(String,String,Object...)} method and by default is formatted
 398  
      * using the {@link MessageFormat#format(String, Object...)} method. If no
 399  
      * pattern is found for key or needs to be overridden, the default pattern
 400  
      * should be returned.
 401  
      * 
 402  
      * @param key the format pattern key
 403  
      * @param defaultPattern the default pattern if no pattern is
 404  
      * @return The format patter for the given key
 405  
      */
 406  
     protected String lookupPattern(String key, String defaultPattern) {
 407  8455
         if (outputPatterns.containsKey(key)) {
 408  3841
             return outputPatterns.getProperty(key);
 409  
         }
 410  4614
         return defaultPattern;
 411  
     }
 412  
 
 413  
     public boolean reportFailureTrace() {
 414  23
         Boolean reportFailure = reportFailureTrace.get();
 415  23
         if ( reportFailure != null ){
 416  19
             return reportFailure;
 417  
         }
 418  4
         return false;
 419  
     }
 420  
 
 421  
     public PrintStreamOutput doReportFailureTrace(boolean reportFailureTrace) {
 422  373
         this.reportFailureTrace.set(reportFailureTrace);
 423  373
         return this;
 424  
     }
 425  
 
 426  
     public boolean compressFailureTrace() {
 427  5
         return compressFailureTrace.get();
 428  
     }
 429  
 
 430  
     public PrintStreamOutput doCompressFailureTrace(boolean compressFailureTrace) {
 431  373
         this.compressFailureTrace.set(compressFailureTrace);
 432  373
         return this;
 433  
     }
 434  
 
 435  
     protected void overwritePattern(String key, String pattern) {
 436  7
         outputPatterns.put(key, pattern);
 437  7
     }
 438  
 
 439  
     /**
 440  
      * Prints text to output stream, replacing parameter start and end
 441  
      * placeholders
 442  
      * 
 443  
      * @param text the String to print
 444  
      */
 445  
     protected void print(String text) {
 446  917
         if (containsTable(text)) {
 447  0
             String tableStart = format(PARAMETER_TABLE_START, PARAMETER_TABLE_START);
 448  0
             String tableEnd = format(PARAMETER_TABLE_END, PARAMETER_TABLE_END);
 449  0
             String tableAsString = substringBetween(text, tableStart, tableEnd);
 450  0
             output.print(text
 451  
                     .replace(tableAsString, formatTable(new ExamplesTable(tableAsString)))
 452  
                     .replace(tableStart, format("parameterValueStart", EMPTY))
 453  
                     .replace(tableEnd, format("parameterValueEnd", EMPTY))
 454  
                     .replace(format(PARAMETER_VALUE_NEWLINE, PARAMETER_VALUE_NEWLINE),
 455  
                             format("parameterValueNewline", "\n")));
 456  0
         } else {
 457  917
             output.print(text
 458  
                     .replace(format(PARAMETER_VALUE_START, PARAMETER_VALUE_START), format("parameterValueStart", EMPTY))
 459  
                     .replace(format(PARAMETER_VALUE_END, PARAMETER_VALUE_END), format("parameterValueEnd", EMPTY))
 460  
                     .replace(format(PARAMETER_VALUE_NEWLINE, PARAMETER_VALUE_NEWLINE),
 461  
                             format("parameterValueNewline", "\n")));
 462  
         }
 463  917
     }
 464  
 
 465  
     private boolean containsTable(String text) {
 466  917
         String tableStart = format(PARAMETER_TABLE_START, PARAMETER_TABLE_START);
 467  917
         String tableEnd = format(PARAMETER_TABLE_END, PARAMETER_TABLE_END);
 468  917
         return text.contains(tableStart) && text.contains(tableEnd);
 469  
     }
 470  
 
 471  
     @Override
 472  
     public String toString() {
 473  0
         return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).append(format).append(output).toString();
 474  
     }
 475  
 
 476  
 }