def bisect_tests(self, spurious_failures):

    test_conflicts = {}
    if not spurious_failures:
        raise ValueError('No failures provided to bisect the cause of')
    for spurious_failure in spurious_failures:
        candidate_causes = self._prior_tests(self.latest_run,
                                             spurious_failure)
        bottom = 0
        top = len(candidate_causes)
        width = top - bottom
        while width:
            check_width = int(math.ceil(width / 2.0))
            test_ids = candidate_causes[
                bottom:bottom + check_width] + [spurious_failure]
            cmd = self.conf.get_run_command(
                test_ids, group_regex=self.group_regex,
                repo_type=self.repo_type, repo_url=self.repo_url,
                serial=self.serial, concurrency=self.concurrency,
                test_path=self.test_path, top_dir=self.top_dir)
            self.run_func(cmd, False,
                          pretty_out=False,
                          repo_type=self.repo_type,
                          repo_url=self.repo_url)
            # check that the test we're probing still failed - still
            # awkward.
            found_fail = []

            def find_fail(test_dict):
                if test_dict['id'] == spurious_failure:
                    found_fail.append(True)

            checker = testtools.StreamToDict(find_fail)
            checker.startTestRun()
            try:
                self.repo.get_failing().get_test().run(checker)
            finally:
                checker.stopTestRun()
            if found_fail:
                # Our conflict is in bottom - clamp the range down.
                top = bottom + check_width
                if width == 1:
                    # found the cause
                    test_conflicts[
                        spurious_failure] = candidate_causes[bottom]
                    width = 0
                else:
                    width = top - bottom
            else:
                # Conflict in the range we did not run: discard bottom.
                bottom = bottom + check_width
                if width == 1:
                    # there will be no more to check, so we didn't
                    # reproduce the failure.
                    width = 0
                else:
                    width = top - bottom
        if spurious_failure not in test_conflicts:
            # Could not determine cause
            test_conflicts[spurious_failure] = 'unknown - no conflicts'
    if test_conflicts:
        table = [('failing test', 'caused by test')]
        for failure in sorted(test_conflicts):
            causes = test_conflicts[failure]
            table.append((failure, causes))
        output.output_table(table)
        return 3
    return 0 def load(force_init=False, in_streams=None,
         subunit_out=False, repo_type='file', repo_url=None,
         run_id=None, streams=None, pretty_out=False, color=False,
         stdout=sys.stdout, abbreviate=False, suppress_attachments=False,
         serial=False, all_attachments=False, show_binary_attachments=False):
    """Load subunit streams into a repository

    This function will load subunit streams into the repository. It will
    output to STDOUT the results from the input stream. Internally this is
    used by the run command to both output the results as well as store the
    result in the repository.

    :param bool force_init: Initialize the specified repository if it hasn't
        been created.
    :param list in_streams: A list of file objects that will be saved into the
        repository
    :param bool subunit_out: Output the subunit stream to stdout
    :param str repo_type: This is the type of repository to use. Valid choices
        are 'file' and 'sql'.
    :param str repo_url: The url of the repository to use.
    :param run_id: The optional run id to save the subunit stream to.
    :param list streams: A list of file paths to read for the input streams.
    :param bool pretty_out: Use the subunit-trace output filter for the loaded
        stream.
    :param bool color: Enabled colorized subunit-trace output
    :param file stdout: The output file to write all output to. By default
        this is sys.stdout
    :param bool abbreviate: Use abbreviated output if set true
    :param bool suppress_attachments: When set true attachments subunit_trace
        will not print attachments on successful test execution.
    :param bool all_attachments: When set true subunit_trace will print all
        text attachments on successful test execution.
    :param bool show_binary_attachments: When set to true, subunit_trace will
        print binary attachments in addition to text attachments.

    :return return_code: The exit code for the command. 0 for success and > 0
        for failures.
    :rtype: int
    """
    try:
        repo = util.get_repo_open(repo_type, repo_url)
    except repository.RepositoryNotFound:
        if force_init:
            try:
                repo = util.get_repo_initialise(repo_type, repo_url)
            except OSError as e:
                if e.errno != errno.EEXIST:
                    raise
                repo_path = repo_url or './stestr'
                stdout.write('The specified repository directory %s already '
                             'exists. Please check if the repository already '
                             'exists or select a different path\n'
                             % repo_path)
                exit(1)
        else:
            raise
    # Not a full implementation of TestCase, but we only need to iterate
    # back to it. Needs to be a callable - its a head fake for
    # testsuite.add.
    if in_streams:
        streams = utils.iter_streams(in_streams, 'subunit')
    elif streams:
        opener = functools.partial(open, mode='rb')
        streams = map(opener, streams)
    else:
        streams = [sys.stdin]

    def mktagger(pos, result):
        return testtools.StreamTagger([result], add=['worker-%d' % pos])

    def make_tests():
        for pos, stream in enumerate(streams):
            # Calls StreamResult API.
            case = subunit.ByteStreamToStreamResult(
                stream, non_subunit_name='stdout')
            decorate = functools.partial(mktagger, pos)
            case = testtools.DecorateTestCaseResult(case, decorate)
            yield (case, str(pos))
    if not run_id:
        inserter = repo.get_inserter()
    else:
        inserter = repo.get_inserter(run_id=run_id)

    retval = 0
    if serial:
        for stream in streams:
            # Calls StreamResult API.
            case = subunit.ByteStreamToStreamResult(
                stream, non_subunit_name='stdout')
            result = _load_case(inserter, repo, case, subunit_out, pretty_out,
                                color, stdout, abbreviate,
                                suppress_attachments, all_attachments,
                                show_binary_attachments)
            if result or retval:
                retval = 1
            else:
                retval = 0
    else:
        case = testtools.ConcurrentStreamTestSuite(make_tests)
        retval = _load_case(inserter, repo, case, subunit_out, pretty_out,
                            color, stdout, abbreviate, suppress_attachments,
                            all_attachments, show_binary_attachments)

    return retval def slowest(repo_type='file', repo_url=None, show_all=False,
            stdout=sys.stdout):
    """Print the slowest times from the last run in the repository

    This function will print to STDOUT the 10 slowests tests in the last run.
    Optionally, using the ``show_all`` argument, it will print all the tests,
    instead of just 10. sorted by time.

    :param str repo_type: This is the type of repository to use. Valid choices
        are 'file' and 'sql'.
    :param str repo_url: The url of the repository to use.
    :param bool show_all: Show timing for all tests.
    :param file stdout: The output file to write all output to. By default
        this is sys.stdout

    :return return_code: The exit code for the command. 0 for success and > 0
        for failures.
    :rtype: int
    """

    repo = util.get_repo_open(repo_type, repo_url)
    try:
        latest_id = repo.latest_id()
    except KeyError:
        return 3
    # what happens when there is no timing info?
    test_times = repo.get_test_times(repo.get_test_ids(latest_id))
    known_times = list(test_times['known'].items())
    known_times.sort(key=itemgetter(1), reverse=True)
    if len(known_times) > 0:
        # By default show 10 rows
        if not show_all:
            known_times = known_times[:10]
        known_times = format_times(known_times)
        header = ('Test id', 'Runtime (s)')
        rows = [header] + known_times
        output.output_table(rows, output=stdout)
    return 0 class TestrConf:
    def __init__(self, config_file, section='DEFAULT'):
    def _sanitize_path(self, path):
    def get_run_command(self, test_ids=None, regexes=None,
                        test_path=None, top_dir=None, group_regex=None,
                        repo_type='file', repo_url=None,
                        serial=False, worker_path=None,
                        concurrency=0,
                        exclude_list=None,
                        include_list=None,
                        exclude_regex=None,
                        randomize=False, parallel_class=None):
            def group_callback(test_id, regex=re.compile(group_regex)): def output_table(table, output=sys.stdout):
    def show_row(row):
def output_tests(tests, output=sys.stdout):
def make_result(get_id, output=sys.stdout):
def output_summary(successful, tests, tests_delta, time, time_delta, values,
                   output=sys.stdout):
def output_stream(stream, output=sys.stdout):
    def __init__(self, process):
    def _append_return_code_as_test(self):
    def read(self, count=-1):
    def readline(self):
    def readlines(self):
class ReturnCodeToSubunit: class AbstractRepositoryFactory:
class AbstractRepository:
class AbstractTestRun:
class RepositoryNotFound(Exception):
    def initialise(self, url):
    def open(self, url):
    def count(self):
    def get_failing(self):
    def get_run_ids(self):
    def remove_run_id(self, run_id):
    def get_inserter(self, partial=False, run_id=None, metadata=None):
    def _get_inserter(self, partial=False, run_id=None, metadata=None):
    def get_latest_run(self):
    def get_test_run(self, run_id):
    def get_test_times(self, test_ids):
    def _get_test_times(self, test_ids):
    def latest_id(self):
    def get_test_ids(self, run_id):
        def gather(test_dict):
    def find_metadata(self, metadata):
    def get_id(self):
    def get_subunit_stream(self):
    def get_test(self):
    def get_metadata(self):
    def __init__(self, url): def _get_default_repo_url(repo_type):
def get_repo_open(repo_type, repo_url=None):
def get_repo_initialise(repo_type, repo_url=None): def wasSuccessful(summary):
    def __init__(self):
    def startTestRun(self):
    def status(self, *args, **kwargs):
    def get_num_failures(self):
    def get_time_taken(self):
    def __init__(self, byte_stream):
    def status(self, test_id=None, test_status=None, test_tags=None,
               runnable=True, file_name=None, file_bytes=None, eof=False,
               mime_type=None, route_code=None, timestamp=None):
    def __init__(self, get_id, stream, previous_run=None):
    def _format_error(self, label, test, error_text, test_tags=None):
    def status(self, **kwargs):
    def _get_previous_summary(self):
    def _output_summary(self, run_id):
    def startTestRun(self):
    def stopTestRun(self):
    def get_summary(self):
class SummarizingResult(testtools.StreamSummary):
class CatFiles(testtools.StreamResult):
class CLITestResult(testtools.StreamResult): def filter_by_ids(suite_or_case, test_ids):
def iterate_tests(test_suite_or_case):
def list_test(test):
    def __init__(self, module='__main__', defaultTest=None, argv=None,
                 testRunner=None, testLoader=unittest.defaultTestLoader,
                 exit=False, verbosity=1, failfast=None, catchbreak=None,
                 buffer=None, warnings=None, tb_locals=False):
    def _getParentArgParser(self):
    def _get_runner(self):
    def runTests(self):
class TestProgram(unittest.TestProgram): def run(self, test):
    "Run the given test case or test suite."
    result, _ = self._list(test)
    result = ExtendedToStreamDecorator(result)
    result = AutoTimingTestResultDecorator(result)
    if self.failfast is not None:
        result.failfast = self.failfast
        result.tb_locals = self.tb_locals
    result.startTestRun()
    try:
        test(result)
    finally:
        result.stopTestRun()
    return result def parse_list(list_bytes):
    """Parse list_bytes into a list of test ids."""
    return _v1(list_bytes) def get_user_config(path=None):
    def __init__(self, path):
    def run(self):
    def failing(self):
    def last(self):
    def load(self):
    def history_list(self):
    def history_show(self):
class UserConfig:
import configparser
import errno
import functools
import io
import os
import subprocess
import sys
import subunit
import testtools
from cliff import command
from stestr import bisect_tests
from stestr.commands import load
from stestr.commands import slowest
from stestr import config_file
from stestr import output
from stestr.repository import abstract as repository
from stestr.repository import util
from stestr import results
from stestr.subunit_runner import program
from stestr.subunit_runner import run as subunit_run
from stestr.testlist import parse_list
from stestr import user_config
class Run(command.Command):
    """Run the tests for a project and store them into the repository.

    Without --subunit, the process exit code will be non-zero if the test
    run was not successful. However, with --subunit, the process exit code
    is non-zero only if the subunit stream could not be generated
    successfully. The test results and run status are included in the
    subunit stream, so the stream should be used to determining the result
    of the run instead of the exit code when using the --subunit flag.
    """

    def get_parser(self, prog_name):
        parser = super().get_parser(prog_name)
        parser.add_argument("filters", nargs="*", default=None,
                            help="A list of string regex filters to initially "
                            "apply on the test list. Tests that match any of "
                            "the regexes will be used. (assuming any other "
                            "filtering specified also uses it)")
        parser.add_argument("--failing", action="store_true",
                            default=False,
                            help="Run only tests known to be failing.")
        parser.add_argument("--serial", action="store_true",
                            default=False,
                            help="Run tests in a serial process.")
        parser.add_argument("--concurrency", action="store", default=None,
                            type=int,
                            help="How many processes to use. The default (0) "
                            "autodetects your CPU count.")
        parser.add_argument("--load-list", default=None,
                            help="Only run tests listed in the named file."),
        parser.add_argument("--subunit", action="store_true", default=False,
                            help="Display results in subunit format.")
        parser.add_argument("--until-failure", action="store_true",
                            default=False,
                            help="Repeat the run again and again until "
                            "failure occurs.")
        parser.add_argument("--analyze-isolation", action="store_true",
                            default=False,
                            help="Search the last test run for 2-test test "
                            "isolation interactions.")
        parser.add_argument("--isolated", action="store_true",
                            default=False,
                            help="Run each test id in a separate test runner.")
        parser.add_argument("--worker-file", action="store", default=None,
                            dest='worker_path',
                            help="Optional path of a manual worker grouping "
                            "file to use for the run")
        parser.add_argument('--exclude-list', '-e',
                            default=None, dest='exclude_list',
                            help='Path to an exclusion list file, this file '
                            'contains a separate regex exclude on each '
                            'newline')
        parser.add_argument('--include-list', '-i',
                            default=None, dest='include_list',
                            help='Path to an inclusion list file, this file '
                            'contains a separate regex on each newline.')
        parser.add_argument('--exclude-regex', '-E', default=None,
                            dest='exclude_regex',
                            help='Test rejection regex. If a test cases name '
                            'matches on re.search() operation , '
                            'it will be removed from the final test list. '
                            'Effectively the exclusion-regexp is added to '
                            'exclusion regexp list, but you do need to edit a '
                            'file. The exclusion filtering happens after the '
                            'initial safe list selection, which by default is '
                            'everything.')
        parser.add_argument('--no-discover', '-n', default=None,
                            metavar='TEST_ID',
                            help="Takes in a single test to bypasses test "
                            "discover and just execute the test specified. A "
                            "file may be used in place of a test name.")
        parser.add_argument('--pdb', default=None, metavar='TEST_ID',
                            help="Run a single test id with the intent of "
                            "using pdb. This does not launch any separate "
                            "processes to ensure pdb works as expected. It "
                            "will bypass test discovery and just execute the "
                            "test specified. A file may be used in place of a "
                            "test name.")
        parser.add_argument('--random', action="store_true",
                            default=False,
                            help="Randomize the test order after they are "
                            "partitioned into separate workers")
        parser.add_argument('--combine', action='store_true', default=False,
                            help="Combine the results from the test run with "
                            "the last run in the repository")
        parser.add_argument('--no-subunit-trace', action='store_true',
                            default=False,
                            help='Disable the default subunit-trace output '
                            'filter')
        parser.add_argument('--force-subunit-trace', action='store_true',
                            default=False,
                            help='Force subunit-trace output regardless of any'
                                 'other options or config settings')
        parser.add_argument('--color', action='store_true', default=False,
                            help='Enable color output in the subunit-trace '
                            'output, if subunit-trace output is enabled. '
                            '(this is the default). If subunit-trace is '
                            'disable this does nothing.')
        parser.add_argument('--slowest', action='store_true', default=False,
                            help='After the test run, print the slowest '
                            'tests.')
        parser.add_argument('--abbreviate', action='store_true',
                            dest='abbreviate',
                            help='Print one character status for each test')
        parser.add_argument('--suppress-attachments', action='store_true',
                            dest='suppress_attachments',
                            help='If set do not print stdout or stderr '
                            'attachment contents on a successful test '
                            'execution')
        parser.add_argument('--all-attachments', action='store_true',
                            dest='all_attachments',
                            help='If set print all text attachment contents on'
                            ' a successful test execution')
        parser.add_argument('--show-binary-attachments', action='store_true',
                            dest='show_binary_attachments',
                            help='If set, show non-text attachments. This is '
                            'generally only useful for debug purposes.')
        return parser

    def take_action(self, parsed_args):

        user_conf = user_config.get_user_config(self.app_args.user_config)