Write UnitTH-style test reports 

        Args:
            suites (:obj:`dict`): dictionary of test suites
            out_dir (:obj:`str`): path to save UnitTH-style test reports
322281
def write_unitth(suites, out_dir):
        
        if not os.path.isdir(out_dir):
            os.mkdir(out_dir)

        for classname, cases in suites.items():
            doc_xml = minidom.Document()

            suite_xml = doc_xml.createElement('testsuite')
            suite_xml.setAttribute('name', classname)
            suite_xml.setAttribute('tests', str(len(cases)))
            suite_xml.setAttribute('errors', str(sum('error' in case for case in cases)))
            suite_xml.setAttribute('failures', str(sum('failure' in case for case in cases)))
            suite_xml.setAttribute('skipped', str(sum('skipped' in case for case in cases)))
            suite_xml.setAttribute('time', '{:.3f}'.format(sum(case['time'] for case in cases)))
            doc_xml.appendChild(suite_xml)

            for case in cases:
                case_xml = doc_xml.createElement('testcase')
                case_xml.setAttribute('classname', classname)
                case_xml.setAttribute('name', case['name'])
                case_xml.setAttribute('time', '{:.3f}'.format(case['time']))
                suite_xml.appendChild(case_xml)

                if 'skipped' in case:
                    skipped_xml = doc_xml.createElement('skipped')
                    skipped_xml.setAttribute('type', case['skipped']['type'])
                    skipped_xml.setAttribute('message', case['skipped']['message'])
                    case_xml.appendChild(skipped_xml)

                    skipped_text_xml = doc_xml.createCDATASection(case['skipped']['text'])
                    skipped_xml.appendChild(skipped_text_xml)

                if 'failure' in case:
                    failure_xml = doc_xml.createElement('failure')
                    failure_xml.setAttribute('type', case['failure']['type'])
                    failure_xml.setAttribute('message', case['failure']['message'])
                    case_xml.appendChild(failure_xml)

                    failure_text_xml = doc_xml.createCDATASection(case['failure']['text'])
                    failure_xml.appendChild(failure_text_xml)

                if 'error' in case:
                    error_xml = doc_xml.createElement('error')
                    error_xml.setAttribute('type', case['error']['type'])
                    error_xml.setAttribute('message', case['error']['message'])
                    case_xml.appendChild(error_xml)

                    error_text_xml = doc_xml.createCDATASection(case['error']['text'])
                    error_xml.appendChild(error_text_xml)

            with open(os.path.join(out_dir, '{}.xml'.format(classname)), 'w') as output:
                doc_xml.writexml(output, encoding='utf-8', addindent='', newl="")
            doc_xml.unlink()
1342510
private void generateSummaryData(List<ISuite> suites) {
        logger.entering(suites);

        SummarizedData tempSuite;
        SummarizedData tempTest;
        SummarizedData tempGroups;
        this.generateTestCaseResultData(suites);

        // Generating Group Summary data
        for (ISuite suite : suites) {

            tempSuite = new SummarizedData();
            tempSuite.setsName(suite.getName());
            Map<String, ISuiteResult> allResults = suite.getResults();
            for (Entry<String, Collection<ITestNGMethod>> sGroupName : suite.getMethodsByGroups().entrySet()) {
                tempGroups = new SummarizedData();
                tempGroups.setsName(sGroupName.getKey());
                tempGroups.incrementiTotal(sGroupName.getValue().size());

                for (TestCaseResult tr : allTestsResults) {
                    if (tr.getGroup().contains(sGroupName.getKey())) {
                        tempGroups.incrementCount(tr.getStatus());
                        tempGroups.incrementDuration(tr.getDurationTaken());
                    }
                }
                tempGroups.setiTotal(tempGroups.getiPassedCount() + tempGroups.getiFailedCount()
                        + tempGroups.getiSkippedCount());
                lGroups.add(tempGroups);

            }

            // Generating Test summary data
            for (ISuiteResult testResult : allResults.values()) {
                ITestContext testContext = testResult.getTestContext();
                tempTest = new SummarizedData();
                tempTest.setsName(testContext.getName());
                tempTest.setiFailedCount(testContext.getFailedTests().size());
                tempTest.setiPassedCount(testContext.getPassedTests().size());
                tempTest.setiSkippedCount(testContext.getSkippedTests().size());
                tempTest.setiTotal(tempTest.getiPassedCount() + tempTest.getiFailedCount()
                        + tempTest.getiSkippedCount());
                tempTest.setlRuntime(testContext.getEndDate().getTime() - testContext.getStartDate().getTime());

                lTests.add(tempTest);
            }

            // Generating Suite Summary data
            for (SummarizedData test : lTests) {

                tempSuite.setiPassedCount(test.getiPassedCount() + tempSuite.getiPassedCount());
                tempSuite.setiFailedCount(test.getiFailedCount() + tempSuite.getiFailedCount());
                tempSuite.setiSkippedCount(tempSuite.getiSkippedCount() + test.getiSkippedCount());
                tempSuite.setiTotal(tempSuite.getiPassedCount() + tempSuite.getiFailedCount()
                        + tempSuite.getiSkippedCount());
                tempSuite.setlRuntime(test.getlRuntime() + tempSuite.getlRuntime());
            }
            lSuites.add(tempSuite);

        }

        Collections.sort(lGroups);
        Collections.sort(lTests);
        logger.exiting();
    }
490192
def wr_xlsx(fout_xlsx, data_xlsx, **kws):
    """"""
    from goatools.wr_tbl_class import WrXlsx
    # optional keyword args: fld2col_widths hdrs prt_if sort_by fld2fmt prt_flds
    items_str = kws.get("items", "items") if "items" not in kws else kws["items"]
    if data_xlsx:
        # Open xlsx file
        xlsxobj = WrXlsx(fout_xlsx, data_xlsx[0]._fields, **kws)
        worksheet = xlsxobj.add_worksheet()
        # Write title (optional) and headers.
        row_idx = xlsxobj.wr_title(worksheet)
        row_idx = xlsxobj.wr_hdrs(worksheet, row_idx)
        row_idx_data0 = row_idx
        # Write data
        row_idx = xlsxobj.wr_data(data_xlsx, row_idx, worksheet)
        # Close xlsx file
        xlsxobj.workbook.close()
        sys.stdout.write("  {N:>5} {ITEMS} WROTE: {FOUT}\n".format(
            N=row_idx-row_idx_data0, ITEMS=items_str, FOUT=fout_xlsx))
    else:
        sys.stdout.write("      0 {ITEMS}. NOT WRITING {FOUT}\n".format(
            ITEMS=items_str, FOUT=fout_xlsx))
589863
function(suite) {
      this.currentSuite = suite
      this.evalBody(suite.body)
      suite.ran = true
      hook('beforeSuite', suite), suite.hook('before')
      each(suite.specs, function(spec) {
        hook('beforeSpec', spec)
        suite.hook('before_each')
        JSpec.runSpec(spec)
        hook('afterSpec', spec)
        suite.hook('after_each')
      })
      if (suite.hasSuites()) {
        each(suite.suites, function(suite) {
          JSpec.runSuite(suite)
        })
      }
      hook('afterSuite', suite), suite.hook('after')
      this.stats.suitesFinished++
    }
933223
def write_dicts_to_csv(self, dicts):
        
        csv_headers = sorted(dicts[0].keys())
        with open(self.path, "w") as out_file:  # write to file
            dict_writer = csv.DictWriter(
                out_file, csv_headers, delimiter=",", quotechar="\""
            )
            dict_writer.writeheader()
            dict_writer.writerows(dicts)
1352394
def _dict_to_report_line(cls, report_dict):
        ''''''
        return '\t'.join([str(report_dict[x]) for x in report.columns])
896940
def load_visible_suites(cls, paths=None):
        
        suite_paths = cls.visible_suite_paths(paths)
        suites = [cls.load(x) for x in suite_paths]
        return suites
736412
def run_suite(case, config, summary):
    
    config["name"] = case
    timing_data = dict()
    model_dir = os.path.join(livvkit.model_dir, config['data_dir'], case)
    bench_dir = os.path.join(livvkit.bench_dir, config['data_dir'], case)
    plot_dir = os.path.join(livvkit.output_dir, "performance", "imgs")
    model_cases = functions.collect_cases(model_dir)
    bench_cases = functions.collect_cases(bench_dir)
    functions.mkdir_p(plot_dir)

    # Generate all of the timing data
    for subcase in sorted(model_cases):
        bench_subcases = bench_cases[subcase] if subcase in bench_cases else []
        timing_data[subcase] = dict()
        for mcase in model_cases[subcase]:
            config["case"] = "-".join([subcase, mcase])
            bpath = (os.path.join(bench_dir, subcase, mcase.replace("-", os.path.sep))
                     if mcase in bench_subcases else None)
            mpath = os.path.join(model_dir, subcase, mcase.replace("-", os.path.sep))
            timing_data[subcase][mcase] = _analyze_case(mpath, bpath, config)

    # Create scaling and timing breakdown plots
    weak_data = weak_scaling(timing_data, config['scaling_var'],
                             config['weak_scaling_points'])
    strong_data = strong_scaling(timing_data, config['scaling_var'],
                                 config['strong_scaling_points'])

    timing_plots = [
        generate_scaling_plot(weak_data,
                              "Weak scaling for " + case.capitalize(),
                              "runtime (s)", "",
                              os.path.join(plot_dir, case + "_weak_scaling.png")
                              ),
        weak_scaling_efficiency_plot(weak_data,
                                     "Weak scaling efficiency for " + case.capitalize(),
                                     "Parallel efficiency (% of linear)", "",
                                     os.path.join(plot_dir, case + "_weak_scaling_efficiency.png")
                                     ),
        generate_scaling_plot(strong_data,
                              "Strong scaling for " + case.capitalize(),
                              "Runtime (s)", "",
                              os.path.join(plot_dir, case + "_strong_scaling.png")
                              ),
        strong_scaling_efficiency_plot(strong_data,
                                       "Strong scaling efficiency for " + case.capitalize(),
                                       "Parallel efficiency (% of linear)", "",
                                       os.path.join(plot_dir,
                                                    case + "_strong_scaling_efficiency.png")
                                       ),
        ]

    timing_plots = timing_plots + \
        [generate_timing_breakdown_plot(timing_data[s],
                                        config['scaling_var'],
                                        "Timing breakdown for " + case.capitalize()+" "+s,
                                        "",
                                        os.path.join(plot_dir, case+"_"+s+"_timing_breakdown.png")
                                        )
         for s in sorted(six.iterkeys(timing_data), key=functions.sort_scale)]

    # Build an image gallery and write the results
    el = [
            elements.gallery("Performance Plots", timing_plots)
         ]
    result = elements.page(case, config["description"], element_list=el)
    summary[case] = _summarize_result(timing_data, config)
    _print_result(case, summary)
    functions.create_page_from_template("performance.html",
                                        os.path.join(livvkit.index_dir, "performance",
                                                     case + ".html"))
    functions.write_json(result, os.path.join(livvkit.output_dir, "performance"),
                         case + ".json")
926507
private String createReportContent(String suiteName, List<TestResult> results, ReportTemplates templates) throws IOException {
        final StringBuilder reportDetails = new StringBuilder();

        for (TestResult result: results) {
            Properties detailProps = new Properties();
            detailProps.put("test.class", result.getClassName());
            detailProps.put("test.name", StringEscapeUtils.escapeXml(result.getTestName()));
            detailProps.put("test.duration", "0.0");

            if (result.isFailed()) {
                detailProps.put("test.error.cause", Optional.ofNullable(result.getCause()).map(Object::getClass).map(Class::getName).orElse(result.getFailureType()));
                detailProps.put("test.error.msg", StringEscapeUtils.escapeXml(result.getErrorMessage()));
                detailProps.put("test.error.stackTrace", Optional.ofNullable(result.getCause()).map(cause -> {
                    StringWriter writer = new StringWriter();
                    cause.printStackTrace(new PrintWriter(writer));
                    return writer.toString();
                }).orElse(result.getFailureStack()));
                reportDetails.append(PropertyUtils.replacePropertiesInString(templates.getFailedTemplate(), detailProps));
            } else {
                reportDetails.append(PropertyUtils.replacePropertiesInString(templates.getSuccessTemplate(), detailProps));
            }
        }

        Properties reportProps = new Properties();
        reportProps.put("test.suite", suiteName);
        reportProps.put("test.cnt", Integer.toString(results.size()));
        reportProps.put("test.skipped.cnt", Long.toString(results.stream().filter(TestResult::isSkipped).count()));
        reportProps.put("test.failed.cnt", Long.toString(results.stream().filter(TestResult::isFailed).count()));
        reportProps.put("test.success.cnt", Long.toString(results.stream().filter(TestResult::isSuccess).count()));
        reportProps.put("test.error.cnt", "0");
        reportProps.put("test.duration", "0.0");
        reportProps.put("tests", reportDetails.toString());
        return PropertyUtils.replacePropertiesInString(templates.getReportTemplate(), reportProps);
    }
650785
private void createGroups(List<ISuite> suites,
                              File outputDirectory) throws Exception
    {
        int index = 1;
        for (ISuite suite : suites)
        {
            SortedMap<String, SortedSet<ITestNGMethod>> groups = sortGroups(suite.getMethodsByGroups());
            if (!groups.isEmpty())
            {
                VelocityContext context = createContext();
                context.put(SUITE_KEY, suite);
                context.put(GROUPS_KEY, groups);
                String fileName = String.format("suite%d_%s", index, GROUPS_FILE);
                generateFile(new File(outputDirectory, fileName),
                             GROUPS_FILE + TEMPLATE_EXTENSION,
                             context);                
            }
            ++index;
        }
    }
226988
def write_type_dumps(self, operations, preserve_order, output_dir):
        
        by_type = {SqlType.INDEX: [], SqlType.FUNCTION: [], SqlType.TRIGGER: []}
        for operation in operations:
            by_type[operation.sql_type].append(operation)

        # optionally sort each operation list by the object name
        if not preserve_order:
            for obj_type, ops in by_type.items():
                by_type[obj_type] = sorted(ops, key=lambda o: o.obj_name)

        if by_type[SqlType.INDEX]:
            self.write_dump('indexes', by_type[SqlType.INDEX], output_dir)
        if by_type[SqlType.FUNCTION]:
            self.write_dump('functions', by_type[SqlType.FUNCTION], output_dir)
        if by_type[SqlType.TRIGGER]:
            self.write_dump('triggers', by_type[SqlType.TRIGGER], output_dir)
136005
def _run_suites suites, type
      # Someone want to explain to me why these are fucking here?
      suites = suites - [MiniTest::Spec]
      suites = suites - [Test::Unit::TestCase] if defined?(Test::Unit::TestCase)

      @turn_suite = Turn::TestSuite.new(@turn_config.suite_name)
      @turn_suite.size = suites.size  #::MiniTest::Unit::TestCase.test_suites.size
      @turn_suite.seed = ::MiniTest::Unit.runner.options[:seed]

      turn_reporter.start_suite(@turn_suite)

      if @turn_config.matchcase
        suites = suites.select{ |suite| @turn_config.matchcase =~ suite.name }
      end

      result = suites.map { |suite| _run_suite(suite, type) }

      turn_reporter.finish_suite(@turn_suite)

      return result
    end
870251
def write(self, presets_path):
        
        if self.builtin:
            raise TypeError("Cannot write built-in preset")

        # Make dictionaries of PresetDefaults values
        odict = self.opts.dict()
        pdict = {self.name: {DESC: self.desc, NOTE: self.note, OPTS: odict}}

        if not os.path.exists(presets_path):
            os.makedirs(presets_path, mode=0o755)

        with open(os.path.join(presets_path, self.name), "w") as pfile:
            json.dump(pdict, pfile)
198308
def do_save(self, arg):
        """"""
        #We need to save the full paths to the staging directories for the tests that are loaded
        #so far; then when the session is restored, we can reparse the results.
        from os import path
        import json
        fullpath = path.expanduser(arg)

        data = {
            "tests": [path.abspath(a.stagedir) for a in list(self.tests.values())],
            "args": self.args
        }

        with open(fullpath, 'w') as f:
            json.dump(data, f)
        msg.okay("Saved current session to {}".format(fullpath))
1174617
def visible_suite_paths(cls, paths=None):
        
        suite_paths = []
        if paths is None:
            paths = os.getenv("PATH", "").split(os.pathsep)
        for path in paths:
            if path and os.path.isdir(path):
                path_ = os.path.dirname(path)
                filepath = os.path.join(path_, "suite.yaml")
                if os.path.isfile(filepath):
                    suite_paths.append(path_)
        return suite_paths
1056110
def dump(self):
        
        report_as_json_string = utils.dict_to_json(self.report)
        if self.out_file:
            utils.string_to_file(self.out_file, report_as_json_string)
        else:
            print report_as_json_string
1130862
function Reporter(options) {
  var _defaultOutputFile = path.resolve(__dirname, '../../protractor-results.txt');
  options.outputFile = options.outputFile || _defaultOutputFile;

  var _root = { appDir: options.appDir, suites: [] };
  log('AppDir: ' + options.appDir, +1);
  var _currentSuite;

  this.suiteStarted = function(suite) {
    _currentSuite = { description: suite.description, status: null, specs: [] };
    _root.suites.push(_currentSuite);
    log('Suite: ' + suite.description, +1);
  };

  this.suiteDone = function(suite) {
    var statuses = _currentSuite.specs.map(function(spec) {
      return spec.status;
    });
    statuses = _.uniq(statuses);
    var status = statuses.indexOf('failed') >= 0 ? 'failed' : statuses.join(', ');
    _currentSuite.status = status;
    log('Suite ' + _currentSuite.status + ': ' + suite.description, -1);
  };

  this.specStarted = function(spec) {

  };

  this.specDone = function(spec) {
    var currentSpec = {
      description: spec.description,
      status: spec.status
    };
    if (spec.failedExpectations.length > 0) {
      currentSpec.failedExpectations = spec.failedExpectations;
    }

    _currentSuite.specs.push(currentSpec);
    log(spec.status + ' - ' + spec.description);
    if (spec.status === 'failed') {
      spec.failedExpectations.forEach(function(err) {
        log(err.message);
      });
    }
  };

  this.jasmineDone = function() {
    outputFile = options.outputFile;
    //// Alternate approach - just stringify the _root - not as pretty
    //// but might be more useful for automation.
    // var output = JSON.stringify(_root, null, 2);
    var output = formatOutput(_root);
    fs.appendFileSync(outputFile, output);
  };

  // for output file output
  function formatOutput(output) {
    var indent = '  ';
    var pad = '  ';
    var results = [];
    results.push('AppDir:' + output.appDir);
    output.suites.forEach(function(suite) {
      results.push(pad + 'Suite: ' + suite.description + ' -- ' + suite.status);
      pad+=indent;
      suite.specs.forEach(function(spec) {
        results.push(pad + spec.status + ' - ' + spec.description);
        if (spec.failedExpectations) {
          pad+=indent;
          spec.failedExpectations.forEach(function (fe) {
            results.push(pad + 'message: ' + fe.message);
          });
          pad=pad.substr(2);
        }
      });
      pad = pad.substr(2);
      results.push('');
    });
    results.push('');
    return results.join('\n');
  }

  // for console output
  var _pad;
  function log(str, indent) {
    _pad = _pad || '';
    if (indent == -1) {
      _pad = _pad.substr(2);
    }
    console.log(_pad + str);
    if (indent == 1) {
      _pad = _pad + '  ';
    }
  }

}