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