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