當前位置: 首頁>>代碼示例>>Python>>正文


Python DocTestRunner.run方法代碼示例

本文整理匯總了Python中doctest.DocTestRunner.run方法的典型用法代碼示例。如果您正苦於以下問題:Python DocTestRunner.run方法的具體用法?Python DocTestRunner.run怎麽用?Python DocTestRunner.run使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在doctest.DocTestRunner的用法示例。


在下文中一共展示了DocTestRunner.run方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: run_doctests

# 需要導入模塊: from doctest import DocTestRunner [as 別名]
# 或者: from doctest.DocTestRunner import run [as 別名]
def run_doctests(module, examples):
    from doctest import DocTest, DocTestRunner, ELLIPSIS

    dt = DocTest(examples, module.__dict__, module.__file__, None, None, None)
    dtr = DocTestRunner(optionflags=ELLIPSIS)

    dtr.run(dt, clear_globs=False)

    return dtr
開發者ID:mahmoud,項目名稱:PythonDoesWhat,代碼行數:11,代碼來源:pdw.py

示例2: run_examples

# 需要導入模塊: from doctest import DocTestRunner [as 別名]
# 或者: from doctest.DocTestRunner import run [as 別名]
    def run_examples(self):
        from doctest import DocTest, DocTestRunner
        examples = sum([part.examples for part in self.parts if isinstance(part, DocTestPart)],[])
        dt = DocTest(examples, self.module.__dict__, self.filename, None, None, None)
        dtr = DocTestRunner()

        def tmp_out(message_to_throw_away):
            # TODO capture error messages, warn
            return

        dtr.run(dt, out=tmp_out, clear_globs=False)
開發者ID:mahmoud,項目名稱:PythonDoesBlog,代碼行數:13,代碼來源:post.py

示例3: test

# 需要導入模塊: from doctest import DocTestRunner [as 別名]
# 或者: from doctest.DocTestRunner import run [as 別名]
 def test(self):
     # Make a new runner per function to be tested
     runner = DocTestRunner(verbose=d2u.verbose)
     for the_test in d2u.finder.find(func, func.__name__):
         runner.run(the_test)
     failed = count_failures(runner)
     if failed:
         # Since we only looked at a single function's docstring,
         # failed should contain at most one item.  More than that
         # is a case we can't handle and should error out on
         if len(failed) > 1:
             err = "Invalid number of test results:" % failed
             raise ValueError(err)
         # Report a normal failure.
         self.fail('failed doctests: %s' % str(failed[0]))
開發者ID:Carreau,項目名稱:ipython,代碼行數:17,代碼來源:ipunittest.py

示例4: run

# 需要導入模塊: from doctest import DocTestRunner [as 別名]
# 或者: from doctest.DocTestRunner import run [as 別名]
    def run(self, test, compileflags=None, out=None, clear_globs=True):
        save_stderr = sys.stderr
        sys.stderr = _SpoofOut()
        
        if self._verbosity > 0:
            print >>save_stderr, (
                self._stderr_term.CYAN+self._stderr_term.BOLD+
                'Testing %s...'%test.name+self._stderr_term.NORMAL)
        try:
            fails, tries = DocTestRunner.run(self, test, compileflags,
                                             out, clear_globs)
        except KeyboardInterrupt:
            if self._current_test is None: raise

            print >>save_stderr, self._failure_header(*self._current_test)
            print >>save_stderr, (
                self._stderr_term.RED+self._stderr_term.BOLD+
                'Keyboard Interrupt!'+self._stderr_term.NORMAL)
        if self._verbosity == 1:
            save_stderr.write(self._stderr_term.CLEAR_LINE)
        if self._verbosity > 0:
            if fails:
                print >>save_stderr, (
                    self._stderr_term.RED+self._stderr_term.BOLD+
                    '  %d example(s) failed!'%fails+self._stderr_term.NORMAL)
            else:
                print >>save_stderr, (
                    self._stderr_term.GREEN+self._stderr_term.BOLD+
                    '  All examples passed'+self._stderr_term.NORMAL)
        print >>save_stderr
        sys.stderr = save_stderr
開發者ID:yochananmkp,項目名稱:clir,代碼行數:33,代碼來源:doctest_driver.py

示例5: DTC_runTest

# 需要導入模塊: from doctest import DocTestRunner [as 別名]
# 或者: from doctest.DocTestRunner import run [as 別名]
 def DTC_runTest(self):
     test = self._dt_test
     old = sys.stdout
     new = StringIO()
     optionflags = self._dt_optionflags
     if not (optionflags & REPORTING_FLAGS):
         # The option flags don't include any reporting flags,
         # so add the default reporting flags
         optionflags |= _unittest_reportflags
     # Patching doctestcase to enable verbose mode
     global g_doctest_verbose
     runner = DocTestRunner(optionflags=optionflags,
                            checker=self._dt_checker,
                            verbose=g_doctest_verbose)
     # End of patch
     try:
         runner.DIVIDER = "-"*70
         failures, tries = runner.run(
             test, out=new.write, clear_globs=False)
     finally:
         sys.stdout = old
     if failures:
         raise self.failureException(self.format_failure(new.getvalue()))
     elif g_doctest_verbose:
         print new.getvalue()
開發者ID:MaxCDN,項目名稱:FunkLoad,代碼行數:27,代碼來源:TestRunner.py

示例6: _import_docstring

# 需要導入模塊: from doctest import DocTestRunner [as 別名]
# 或者: from doctest.DocTestRunner import run [as 別名]
def _import_docstring(documenter):
    code_content = _import_docstring_code_content(documenter)
    if code_content:
        # noinspection PyBroadException
        try:
            code, content = code_content
            parser = DocTestParser()
            runner = DocTestRunner(verbose=0,
                                   optionflags=NORMALIZE_WHITESPACE | ELLIPSIS)

            glob = {}
            if documenter.modname:
                exec('from %s import *\n' % documenter.modname, glob)

            tests = parser.get_doctest(code, glob, '', '', 0)
            runner.run(tests, clear_globs=False)

            documenter.object = tests.globs[documenter.name]
            documenter.code = content
            documenter.is_doctest = True
            return True
        except Exception:
            pass
開發者ID:vinci1it2000,項目名稱:dispatcher,代碼行數:25,代碼來源:documenter.py

示例7: run_test

# 需要導入模塊: from doctest import DocTestRunner [as 別名]
# 或者: from doctest.DocTestRunner import run [as 別名]
def run_test(doctest):
	summary = StringIO()
	runner = DocTestRunner(optionflags=REPORT_NDIFF)
	runner.run(doctest, out=summary.write)

	assert runner.failures == 0, '\n' + summary.getvalue()
開發者ID:EvanKrall,項目名稱:Testify,代碼行數:8,代碼來源:doctestcase.py

示例8: TestingProtocol

# 需要導入模塊: from doctest import DocTestRunner [as 別名]
# 或者: from doctest.DocTestRunner import run [as 別名]
class TestingProtocol(models.Protocol):
    """A Protocol that executes doctests as lists of Example objects, supports 
    suite/case specificity, alternate file testing, and provides users with 
    details such as cases passed and test coverage.
    """
    def __init__(self, args, assignment):
        super().__init__(args, assignment)
        # The environment in which the doctests are run (global vars)
        self.good_env = {}
        self.verb = self.args.verbose
        # Initialize the doctest module objects that will do the testing/parse
        self.parser = DocTestParser()
        self.runner = DocTestRunner(verbose=self.verb, optionflags=FAIL_FAST)
        self.lines_exec = 0
        self.lines_total = 0


    def test(self, good_env={}, suite=None, case=None):
        test_results = {}
        # all examples to be run will be put in exs
        exs = collections.OrderedDict()
        # use regex to get raw strings organized into suite/case
        self.get_data()
        try:
            if suite:
                exs = self.get_suite_examples(suite, case)
            elif case:
                # No support for cases without their suite
                raise EarlyExit('python3 ok: error: ' 
                    'Please specify suite for given case ({}).'.format(case[0]))
            else:
                exs = self.get_all_examples()
            # gets analytics to be returned
            test_results[self.tstfile_name] =  self.analyze(suite, case, exs)
        except KeyError as e:
            raise EarlyExit('python3 ok: error: ' 
                    'Suite/Case label must be valid.'
                    '(Suites: {}, Cases: {})'.format(self.num_suites, self.num_cases))
        return test_results

    def analyze(self, suite, case, examples):
        failed, attempted = self.run_examples(examples)
        self.cov.stop()
        passed = attempted - failed
        format.print_test_progress_bar( '{} summary'.format(self.tstfile_name), 
                                        passed, failed, verbose=self.verb)
        # only support test coverage stats when running everything
        if not suite:
            self.print_coverage()
            if self.args.coverage:
                if self.lines_exec == self.lines_total:
                    print("Maximum coverage achieved! Great work!")
                else:
                    self.give_suggestions()
        return {'suites_total' : self.num_suites, 'cases_total': self.num_cases, 
                'exs_failed' : failed, 'exs_passed' : passed, 'attempted' : attempted,
                'actual_cov' : self.lines_exec, 'total_cov' : self.lines_total}

    def give_suggestions(self):
        print("Consider adding tests for the following:")
        for file in self.clean_src:
            file += '.py'
            cov_stats = self.cov.analysis2(file)
            missing_cov = cov_stats[3]
            if missing_cov:
                print('   File: {}'.format(file))
                missing_string = '      Line(s): ' + ','.join(map(str, missing_cov)) 
                print(missing_string)



    def get_suite_examples(self, suite, case):
        # suite/case specified, so only parse relevant text into Examples
        exs = collections.OrderedDict()
        case_ex = collections.OrderedDict()
        # get the shared lines that should impact all the cases in the suite.
        shrd_txt = self.shared_case_data[suite]
        if shrd_txt:
            parse_shared = self.parser.parse(shrd_txt.group(0), self.tstfile_name)
            shrd_ex = [i for i in parse_shared if isinstance(i, Example)]
            if shrd_ex:
                case_ex['shared'] = shrd_ex
        if case:
            if str(case[0]) not in self.data[suite]:
                 raise KeyError
            parsed_temp_examples = self.parser.parse(self.data[suite][case[0]], self.tstfile_name)
            case_examples = [i for i in parsed_temp_examples if isinstance(i, Example)]
            case_ex[str(case[0])] = case_examples
        else:
            for itemcase in self.data[suite].keys():
                parsed_temp_examples = self.parser.parse(self.data[suite][itemcase], self.tstfile_name)
                case_examples = [i for i in parsed_temp_examples if isinstance(i, Example)]
                case_ex[itemcase] = case_examples
        exs[suite] = case_ex
        return exs


    def get_all_examples(self):
        # no suite/case flag, so parses all text into Example objects
        exs = collections.OrderedDict()
#.........這裏部分代碼省略.........
開發者ID:shamhub,項目名稱:python_programming,代碼行數:103,代碼來源:testing.py


注:本文中的doctest.DocTestRunner.run方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。