
/**
 * Module dependencies.
 */

var Base = require('./base')
  , utils = require('../utils')
  , escape = utils.escape;

/**
 * Expose `XUnit`.
 */

exports = module.exports = XUnit;

/**
 * Initialize a new `XUnit` reporter.
 *
 * @param {Runner} runner
 * @api public
 */

function XUnit(runner) {
  Base.call(this, runner);
  var stats = this.stats
    , tests = []
    , self = this;

  runner.on('test end', function(test){
    tests.push(test);
  });

  runner.on('end', function(){
    console.error(tag('testsuite', {
        name: 'Mocha Tests'
      , tests: stats.tests
      , failures: stats.failures
      , skip: stats.tests - stats.failures - stats.passes
      , timestamp: (new Date).toUTCString()
      , time: stats.duration / 1000
    }, false));

    tests.forEach(test);
    console.error('</testsuite>');    
  });
}

/**
 * Inherit from `Base.prototype`.
 */

XUnit.prototype.__proto__ = Base.prototype;

/**
 * Output tag for the given `test.`
 */

function test(test) {
  var attrs = {
      classname: test.fullTitle()
    , name: test.title
    , time: test.duration / 1000
  };

  if (test.failed) {
    var err = test.err;
    attrs.message = escape(err.message);
    console.error(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack))));
  } else if (test.pending) {
    console.error(tag('testcase', attrs, false, tag('skipped', {}, true)));
  } else {
    console.error(tag('testcase', attrs, true) );
  }
}

/**
 * HTML tag helper.
 */

function tag(name, attrs, close, content) {
  var end = close ? '/>' : '>'
    , pairs = []
    , tag;

  for (var key in attrs) {
    pairs.push(key + '="' + escape(attrs[key]) + '"');
  }

  tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
  if (content) tag += content + '</' + name + end;
  return tag;
}

/**
 * Return cdata escaped CDATA `str`.
 */

function cdata(str) {
  return '<![CDATA[' + escape(str) + ']]>';
}

@@ -488,37 +488,35 @@
 ()%7B%0A    console.
-error
+log
 (tag('testsuite'
@@ -799,21 +799,19 @@
 console.
-error
+log
 ('%3C/test
@@ -1190,37 +1190,35 @@
 e);%0A    console.
-error
+log
 (tag('testcase',
@@ -1315,37 +1315,35 @@
 ) %7B%0A    console.
-error
+log
 (tag('testcase',
@@ -1412,13 +1412,11 @@
 ole.
-error
+log
 (tag

output xunit to stdout