Python doctest.testmod() Examples

The following are 60 code examples for showing how to use doctest.testmod(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

You may also check out all available functions/classes of the module doctest , or try the search function .

Example 1
Project: pg_simple   Author: masroore   File: main.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_basic_functions(self):
        import code
        import doctest
        import sys

        db = pg_simple.PgSimple(self.pool)
        if sys.argv.count('--interact'):
            db.log = sys.stdout
            code.interact(local=locals())
        else:
            try:
                # Setup tables
                self._drop_tables(db)
                self._create_tables(db, fill=True)
                # Run tests
                doctest.testmod(optionflags=doctest.ELLIPSIS)
            finally:
                # Drop tables
                self._drop_tables(db)
        self.assertEqual(True, True) 
Example 2
Project: mishkal   Author: linuxscout   File: doctest24.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, verbose=False, parser=DocTestParser(),
                 recurse=True, _namefilter=None, exclude_empty=True):
        """
        Create a new doctest finder.

        The optional argument `parser` specifies a class or
        function that should be used to create new DocTest objects (or
        objects that implement the same interface as DocTest).  The
        signature for this factory function should match the signature
        of the DocTest constructor.

        If the optional argument `recurse` is false, then `find` will
        only examine the given object, and not any contained objects.

        If the optional argument `exclude_empty` is false, then `find`
        will include tests for objects with empty docstrings.
        """
        self._parser = parser
        self._verbose = verbose
        self._recurse = recurse
        self._exclude_empty = exclude_empty
        # _namefilter is undocumented, and exists only for temporary backward-
        # compatibility support of testmod's deprecated isprivate mess.
        self._namefilter = _namefilter 
Example 3
Project: tidb-docker-compose   Author: pingcap   File: session.py    License: Apache License 2.0 6 votes vote down vote up
def _test():
    import os
    import doctest
    from pyspark.context import SparkContext
    from pyspark.sql import Row
    import pyspark.sql.session

    os.chdir(os.environ["SPARK_HOME"])

    globs = pyspark.sql.session.__dict__.copy()
    sc = SparkContext('local[4]', 'PythonTest')
    globs['sc'] = sc
    globs['spark'] = SparkSession(sc)
    globs['rdd'] = rdd = sc.parallelize(
        [Row(field1=1, field2="row1"),
         Row(field1=2, field2="row2"),
         Row(field1=3, field2="row3")])
    globs['df'] = rdd.toDF()
    (failure_count, test_count) = doctest.testmod(
        pyspark.sql.session, globs=globs,
        optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
    globs['sc'].stop()
    if failure_count:
        sys.exit(-1) 
Example 4
Project: tidb-docker-compose   Author: pingcap   File: session.py    License: Apache License 2.0 6 votes vote down vote up
def _test():
    import os
    import doctest
    from pyspark.context import SparkContext
    from pyspark.sql import Row
    import pyspark.sql.session

    os.chdir(os.environ["SPARK_HOME"])

    globs = pyspark.sql.session.__dict__.copy()
    sc = SparkContext('local[4]', 'PythonTest')
    globs['sc'] = sc
    globs['spark'] = SparkSession(sc)
    globs['rdd'] = rdd = sc.parallelize(
        [Row(field1=1, field2="row1"),
         Row(field1=2, field2="row2"),
         Row(field1=3, field2="row3")])
    globs['df'] = rdd.toDF()
    (failure_count, test_count) = doctest.testmod(
        pyspark.sql.session, globs=globs,
        optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
    globs['sc'].stop()
    if failure_count:
        exit(-1) 
Example 5
Project: fungrim   Author: fredrik-johansson   File: __init__.py    License: MIT License 6 votes vote down vote up
def test():
    import doctest

    print("----------------------------------------------------------")
    print("expr")
    print("----------------------------------------------------------")
    doctest.testmod(expr, verbose=True, raise_on_error=False, optionflags=doctest.ELLIPSIS)
    expr.TestExpr().run()

    print("----------------------------------------------------------")
    print("algebraic")
    print("----------------------------------------------------------")
    doctest.testmod(algebraic, verbose=True, raise_on_error=True, optionflags=doctest.ELLIPSIS)
    algebraic.TestAlgebraic().run()

    print("----------------------------------------------------------")
    print("brain")
    print("----------------------------------------------------------")
    doctest.testmod(brain, verbose=True, raise_on_error=True, optionflags=doctest.ELLIPSIS)
    TestBrain().run() 
Example 6
Project: meddle   Author: glmcdona   File: doctest.py    License: MIT License 6 votes vote down vote up
def _test():
    testfiles = [arg for arg in sys.argv[1:] if arg and arg[0] != '-']
    if not testfiles:
        name = os.path.basename(sys.argv[0])
        if '__loader__' in globals():          # python -m
            name, _ = os.path.splitext(name)
        print("usage: {0} [-v] file ...".format(name))
        return 2
    for filename in testfiles:
        if filename.endswith(".py"):
            # It is a module -- insert its dir into sys.path and try to
            # import it. If it is part of a package, that possibly
            # won't work because of package imports.
            dirname, filename = os.path.split(filename)
            sys.path.insert(0, dirname)
            m = __import__(filename[:-3])
            del sys.path[0]
            failures, _ = testmod(m)
        else:
            failures, _ = testfile(filename, module_relative=False)
        if failures:
            return 1
    return 0 
Example 7
Project: pledgeservice   Author: MayOneUS   File: doctest.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, verbose=False, parser=DocTestParser(),
                 recurse=True, _namefilter=None, exclude_empty=True):
        """
        Create a new doctest finder.

        The optional argument `parser` specifies a class or
        function that should be used to create new DocTest objects (or
        objects that implement the same interface as DocTest).  The
        signature for this factory function should match the signature
        of the DocTest constructor.

        If the optional argument `recurse` is false, then `find` will
        only examine the given object, and not any contained objects.

        If the optional argument `exclude_empty` is false, then `find`
        will include tests for objects with empty docstrings.
        """
        self._parser = parser
        self._verbose = verbose
        self._recurse = recurse
        self._exclude_empty = exclude_empty
        # _namefilter is undocumented, and exists only for temporary backward-
        # compatibility support of testmod's deprecated isprivate mess.
        self._namefilter = _namefilter 
Example 8
Project: ironpython2   Author: IronLanguages   File: doctest.py    License: Apache License 2.0 6 votes vote down vote up
def _test():
    testfiles = [arg for arg in sys.argv[1:] if arg and arg[0] != '-']
    if not testfiles:
        name = os.path.basename(sys.argv[0])
        if '__loader__' in globals():          # python -m
            name, _ = os.path.splitext(name)
        print("usage: {0} [-v] file ...".format(name))
        return 2
    for filename in testfiles:
        if filename.endswith(".py"):
            # It is a module -- insert its dir into sys.path and try to
            # import it. If it is part of a package, that possibly
            # won't work because of package imports.
            dirname, filename = os.path.split(filename)
            sys.path.insert(0, dirname)
            m = __import__(filename[:-3])
            del sys.path[0]
            failures, _ = testmod(m)
        else:
            failures, _ = testfile(filename, module_relative=False)
        if failures:
            return 1
    return 0 
Example 9
Project: locality-sensitive-hashing   Author: singhj   File: dtcompat.py    License: MIT License 6 votes vote down vote up
def __init__(self, verbose=False, parser=DocTestParser(),
                 recurse=True, _namefilter=None, exclude_empty=True):
        """
        Create a new doctest finder.

        The optional argument `parser` specifies a class or
        function that should be used to create new DocTest objects (or
        objects that implement the same interface as DocTest).  The
        signature for this factory function should match the signature
        of the DocTest constructor.

        If the optional argument `recurse` is false, then `find` will
        only examine the given object, and not any contained objects.

        If the optional argument `exclude_empty` is false, then `find`
        will include tests for objects with empty docstrings.
        """
        self._parser = parser
        self._verbose = verbose
        self._recurse = recurse
        self._exclude_empty = exclude_empty
        # _namefilter is undocumented, and exists only for temporary backward-
        # compatibility support of testmod's deprecated isprivate mess.
        self._namefilter = _namefilter 
Example 10
Project: adaptfilt   Author: Wramberg   File: __init__.py    License: MIT License 6 votes vote down vote up
def rundoctests(verbose=False):
    """
    Executes doctests
    """
    import doctest
    import lms as testmod1
    import nlms as testmod2
    import ap as testmod3
    import misc as testmod4
    import nlmsru as testmod5
    lmsres = doctest.testmod(testmod1, verbose=verbose)
    nlmsres = doctest.testmod(testmod2, verbose=verbose)
    apres = doctest.testmod(testmod3, verbose=verbose)
    miscres = doctest.testmod(testmod4, verbose=verbose)
    nlmsrures = doctest.testmod(testmod5, verbose=verbose)
    print '   LMS: ', lmsres
    print '  NLMS: ', nlmsres
    print 'NLMSRU: ', nlmsrures
    print '    AP: ', apres
    print '  MISC: ', miscres 
Example 11
Project: BinderFilter   Author: dxwu   File: doctest.py    License: MIT License 6 votes vote down vote up
def _test():
    testfiles = [arg for arg in sys.argv[1:] if arg and arg[0] != '-']
    if not testfiles:
        name = os.path.basename(sys.argv[0])
        if '__loader__' in globals():          # python -m
            name, _ = os.path.splitext(name)
        print("usage: {0} [-v] file ...".format(name))
        return 2
    for filename in testfiles:
        if filename.endswith(".py"):
            # It is a module -- insert its dir into sys.path and try to
            # import it. If it is part of a package, that possibly
            # won't work because of package imports.
            dirname, filename = os.path.split(filename)
            sys.path.insert(0, dirname)
            m = __import__(filename[:-3])
            del sys.path[0]
            failures, _ = testmod(m)
        else:
            failures, _ = testfile(filename, module_relative=False)
        if failures:
            return 1
    return 0 
Example 12
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_docstring.py    License: Apache License 2.0 5 votes vote down vote up
def test_symbols():
    globs = {'np': numpy, 'mx': mxnet, 'test_utils': mxnet.test_utils, 'SymbolDoc': mxnet.symbol_doc.SymbolDoc}

    # make sure all the operators are available
    import_into(globs, mxnet.symbol)
    doctest.testmod(mxnet.symbol_doc, globs=globs, verbose=True) 
Example 13
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_docstring.py    License: Apache License 2.0 5 votes vote down vote up
def test_ndarray():
    globs = {'np': numpy, 'mx': mxnet}

    doctest.testmod(mxnet.ndarray, globs=globs, verbose=True) 
Example 14
Project: OpenFermion-Cirq   Author: quantumlib   File: run_doctest.py    License: Apache License 2.0 5 votes vote down vote up
def run(self) -> doctest.TestResults:
        return doctest.testmod(self.mod,
                               globs=self.test_globals,
                               report=False,
                               verbose=False) 
Example 15
Project: jawfish   Author: war-and-code   File: difflib.py    License: MIT License 5 votes vote down vote up
def _test():
    import doctest, difflib
    return doctest.testmod(difflib) 
Example 16
Project: jawfish   Author: war-and-code   File: support.py    License: MIT License 5 votes vote down vote up
def run_doctest(module, verbosity=None, optionflags=0):
    """Run doctest on the given module.  Return (#failures, #tests).

    If optional argument verbosity is not specified (or is None), pass
    support's belief about verbosity on to doctest.  Else doctest's
    usual behavior is used (it searches sys.argv for -v).
    """

    import doctest

    if verbosity is None:
        verbosity = verbose
    else:
        verbosity = None

    f, t = doctest.testmod(module, verbose=verbosity, optionflags=optionflags)
    if f:
        raise TestFailed("%d of %d doctests failed" % (f, t))
    if verbose:
        print('doctest (%s) ... %d tests with zero failures' %
              (module.__name__, t))
    return f, t


#=======================================================================
# Support for saving and restoring the imported modules. 
Example 17
Project: razzy-spinner   Author: rafasashi   File: wntools.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _test(reset=0):
    import doctest, wntools
    if reset:
        doctest.master = None # This keeps doctest from complaining after a reload.
    return doctest.testmod(wntools) 
Example 18
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _test(reset=0):
    import doctest, wordnet
    if reset:
        doctest.master = None # This keeps doctest from complaining after a reload.
    return doctest.testmod(wordnet) 
Example 19
Project: razzy-spinner   Author: rafasashi   File: featurelite.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test():
    "Run unit tests on unification."
    import doctest
    doctest.testmod() 
Example 20
Project: razzy-spinner   Author: rafasashi   File: wntools.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _test(reset=0):
    import doctest, wntools
    if reset:
        doctest.master = None # This keeps doctest from complaining after a reload.
    return doctest.testmod(wntools) 
Example 21
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _test(reset=0):
    import doctest, wordnet
    if reset:
        doctest.master = None # This keeps doctest from complaining after a reload.
    return doctest.testmod(wordnet) 
Example 22
Project: verge3d-blender-addon   Author: Soft8Soft   File: support.py    License: GNU General Public License v3.0 5 votes vote down vote up
def run_doctest(module, verbosity=None, optionflags=0):
    """Run doctest on the given module.  Return (#failures, #tests).

    If optional argument verbosity is not specified (or is None), pass
    support's belief about verbosity on to doctest.  Else doctest's
    usual behavior is used (it searches sys.argv for -v).
    """

    import doctest

    if verbosity is None:
        verbosity = verbose
    else:
        verbosity = None

    f, t = doctest.testmod(module, verbose=verbosity, optionflags=optionflags)
    if f:
        raise TestFailed("%d of %d doctests failed" % (f, t))
    if verbose:
        print('doctest (%s) ... %d tests with zero failures' %
              (module.__name__, t))
    return f, t


#=======================================================================
# Support for saving and restoring the imported modules. 
Example 23
Project: recruit   Author: Frank-qlu   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def _test():
    import doctest
    sys.path.insert(0, os.pardir)
    import pytz
    return doctest.testmod(pytz) 
Example 24
Project: recruit   Author: Frank-qlu   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def _test():
    import doctest
    sys.path.insert(0, os.pardir)
    import pytz
    return doctest.testmod(pytz) 
Example 25
Project: dsub   Author: DataBiosphere   File: dsub_test.py    License: Apache License 2.0 5 votes vote down vote up
def test_doctest(self):
    result = doctest.testmod(dsub_command, report=True)
    self.assertEqual(0, result.failed) 
Example 26
Project: dsub   Author: DataBiosphere   File: job_model_test.py    License: Apache License 2.0 5 votes vote down vote up
def test_doctest(self):
    result = doctest.testmod(job_model, report=True)
    self.assertEqual(0, result.failed) 
Example 27
Project: dsub   Author: DataBiosphere   File: param_util_test.py    License: Apache License 2.0 5 votes vote down vote up
def test_doctest(self):
    result = doctest.testmod(param_util, report=True)
    self.assertEqual(0, result.failed) 
Example 28
Project: script.tvguide.fullscreen   Author: primaeval   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _test():
    import doctest, os, sys
    sys.path.insert(0, os.pardir)
    import pytz
    return doctest.testmod(pytz) 
Example 29
Project: mishkal   Author: linuxscout   File: doctest24.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, checker=None, verbose=None, optionflags=0):
        """
        Create a new test runner.

        Optional keyword arg `checker` is the `OutputChecker` that
        should be used to compare the expected outputs and actual
        outputs of doctest examples.

        Optional keyword arg 'verbose' prints lots of stuff if true,
        only failures if false; by default, it's true iff '-v' is in
        sys.argv.

        Optional argument `optionflags` can be used to control how the
        test runner compares expected output to actual output, and how
        it displays failures.  See the documentation for `testmod` for
        more information.
        """
        self._checker = checker or OutputChecker()
        if verbose is None:
            verbose = '-v' in sys.argv
        self._verbose = verbose
        self.optionflags = optionflags
        self.original_optionflags = optionflags

        # Keep track of the examples we've run.
        self.tries = 0
        self.failures = 0
        self._name2ft = {}

        # Create a fake output target for capturing doctest output.
        self._fakeout = _SpoofOut()

    #/////////////////////////////////////////////////////////////////
    # Reporting methods
    #///////////////////////////////////////////////////////////////// 
Example 30
Project: mishkal   Author: linuxscout   File: doctest24.py    License: GNU General Public License v3.0 5 votes vote down vote up
def report_failure(self, out, test, example, got):
        raise DocTestFailure(test, example, got)

######################################################################
## 6. Test Functions
######################################################################
# These should be backwards compatible.

# For backward compatibility, a global instance of a DocTestRunner
# class, updated by testmod. 
Example 31
Project: mishkal   Author: linuxscout   File: doctest24.py    License: GNU General Public License v3.0 5 votes vote down vote up
def run_docstring_examples(f, globs, verbose=False, name="NoName",
                           compileflags=None, optionflags=0):
    """
    Test examples in the given object's docstring (`f`), using `globs`
    as globals.  Optional argument `name` is used in failure messages.
    If the optional argument `verbose` is true, then generate output
    even if there are no failures.

    `compileflags` gives the set of flags that should be used by the
    Python compiler when running the examples.  If not specified, then
    it will default to the set of future-import flags that apply to
    `globs`.

    Optional keyword arg `optionflags` specifies options for the
    testing and output.  See the documentation for `testmod` for more
    information.
    """
    # Find, parse, and run all tests in the given module.
    finder = DocTestFinder(verbose=verbose, recurse=False)
    runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
    for test in finder.find(f, name, globs=globs):
        runner.run(test, compileflags=compileflags)

######################################################################
## 7. Tester
######################################################################
# This is provided only for backwards compatibility.  It's not
# actually used in any way. 
Example 32
Project: MatchingMarkets.py   Author: QuantEcon   File: pulp.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def pulpDoctest():
    """
    runs all doctests
    """
    import doctest
    if __name__ != '__main__':
        from . import pulp
        doctest.testmod(pulp)
    else:
        doctest.testmod() 
Example 33
Project: android_rinex   Author: rokubun   File: andrnx.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_doctests_gnsslogger(self):
        import andrnx.gnsslogger
        fails, tests = doctest.testmod(andrnx.gnsslogger)
        self.assertEqual(fails, 0) 
Example 34
Project: meddle   Author: glmcdona   File: Cookie.py    License: MIT License 5 votes vote down vote up
def _test():
    import doctest, Cookie
    return doctest.testmod(Cookie) 
Example 35
Project: meddle   Author: glmcdona   File: difflib.py    License: MIT License 5 votes vote down vote up
def _test():
    import doctest, difflib
    return doctest.testmod(difflib) 
Example 36
Project: meddle   Author: glmcdona   File: pickle.py    License: MIT License 5 votes vote down vote up
def _test():
    import doctest
    return doctest.testmod() 
Example 37
Project: meddle   Author: glmcdona   File: doctest.py    License: MIT License 5 votes vote down vote up
def __init__(self, checker=None, verbose=None, optionflags=0):
        """
        Create a new test runner.

        Optional keyword arg `checker` is the `OutputChecker` that
        should be used to compare the expected outputs and actual
        outputs of doctest examples.

        Optional keyword arg 'verbose' prints lots of stuff if true,
        only failures if false; by default, it's true iff '-v' is in
        sys.argv.

        Optional argument `optionflags` can be used to control how the
        test runner compares expected output to actual output, and how
        it displays failures.  See the documentation for `testmod` for
        more information.
        """
        self._checker = checker or OutputChecker()
        if verbose is None:
            verbose = '-v' in sys.argv
        self._verbose = verbose
        self.optionflags = optionflags
        self.original_optionflags = optionflags

        # Keep track of the examples we've run.
        self.tries = 0
        self.failures = 0
        self._name2ft = {}

        # Create a fake output target for capturing doctest output.
        self._fakeout = _SpoofOut()

    #/////////////////////////////////////////////////////////////////
    # Reporting methods
    #///////////////////////////////////////////////////////////////// 
Example 38
Project: meddle   Author: glmcdona   File: doctest.py    License: MIT License 5 votes vote down vote up
def report_failure(self, out, test, example, got):
        raise DocTestFailure(test, example, got)

######################################################################
## 6. Test Functions
######################################################################
# These should be backwards compatible.

# For backward compatibility, a global instance of a DocTestRunner
# class, updated by testmod. 
Example 39
Project: meddle   Author: glmcdona   File: pickletools.py    License: MIT License 5 votes vote down vote up
def _test():
    import doctest
    return doctest.testmod() 
Example 40
Project: pledgeservice   Author: MayOneUS   File: doctest.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, checker=None, verbose=None, optionflags=0):
        """
        Create a new test runner.

        Optional keyword arg `checker` is the `OutputChecker` that
        should be used to compare the expected outputs and actual
        outputs of doctest examples.

        Optional keyword arg 'verbose' prints lots of stuff if true,
        only failures if false; by default, it's true iff '-v' is in
        sys.argv.

        Optional argument `optionflags` can be used to control how the
        test runner compares expected output to actual output, and how
        it displays failures.  See the documentation for `testmod` for
        more information.
        """
        self._checker = checker or OutputChecker()
        if verbose is None:
            verbose = '-v' in sys.argv
        self._verbose = verbose
        self.optionflags = optionflags
        self.original_optionflags = optionflags

        # Keep track of the examples we've run.
        self.tries = 0
        self.failures = 0
        self._name2ft = {}

        # Create a fake output target for capturing doctest output.
        self._fakeout = _SpoofOut()

    #/////////////////////////////////////////////////////////////////
    # Reporting methods
    #///////////////////////////////////////////////////////////////// 
Example 41
Project: pledgeservice   Author: MayOneUS   File: doctest.py    License: Apache License 2.0 5 votes vote down vote up
def report_failure(self, out, test, example, got):
        raise DocTestFailure(test, example, got)

######################################################################
## 6. Test Functions
######################################################################
# These should be backwards compatible.

# For backward compatibility, a global instance of a DocTestRunner
# class, updated by testmod. 
Example 42
Project: pledgeservice   Author: MayOneUS   File: doctest.py    License: Apache License 2.0 5 votes vote down vote up
def run_docstring_examples(f, globs, verbose=False, name="NoName",
                           compileflags=None, optionflags=0):
    """
    Test examples in the given object's docstring (`f`), using `globs`
    as globals.  Optional argument `name` is used in failure messages.
    If the optional argument `verbose` is true, then generate output
    even if there are no failures.

    `compileflags` gives the set of flags that should be used by the
    Python compiler when running the examples.  If not specified, then
    it will default to the set of future-import flags that apply to
    `globs`.

    Optional keyword arg `optionflags` specifies options for the
    testing and output.  See the documentation for `testmod` for more
    information.
    """
    # Find, parse, and run all tests in the given module.
    finder = DocTestFinder(verbose=verbose, recurse=False)
    runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
    for test in finder.find(f, name, globs=globs):
        runner.run(test, compileflags=compileflags)

######################################################################
## 7. Tester
######################################################################
# This is provided only for backwards compatibility.  It's not
# actually used in any way. 
Example 43
Project: Clean-Code-in-Python   Author: PacktPublishing   File: indices.py    License: MIT License 5 votes vote down vote up
def main():
    index_last()
    get_slices()
    fail_count, _ = doctest.testmod(verbose=True)
    raise SystemExit(fail_count) 
Example 44
Project: Clean-code-in-Python   Author: rmariano   File: indices.py    License: MIT License 5 votes vote down vote up
def main():
    index_last()
    get_slices()
    fail_count, _ = doctest.testmod(verbose=True)
    raise SystemExit(fail_count) 
Example 45
Project: ironpython2   Author: IronLanguages   File: Cookie.py    License: Apache License 2.0 5 votes vote down vote up
def _test():
    import doctest, Cookie
    return doctest.testmod(Cookie) 
Example 46
Project: ironpython2   Author: IronLanguages   File: test_objects.py    License: Apache License 2.0 5 votes vote down vote up
def test(self):
        failures, tests = doctest.testmod(ctypes.test.test_objects)
        self.assertFalse(failures, 'doctests failed, see output above') 
Example 47
Project: ironpython2   Author: IronLanguages   File: test_win32timezone.py    License: Apache License 2.0 5 votes vote down vote up
def testWin32TZ(self):
        failed, total = doctest.testmod( win32timezone, verbose = False )
        self.failIf( failed ) 
Example 48
Project: ironpython2   Author: IronLanguages   File: difflib.py    License: Apache License 2.0 5 votes vote down vote up
def _test():
    import doctest, difflib
    return doctest.testmod(difflib) 
Example 49
Project: ironpython2   Author: IronLanguages   File: pickle.py    License: Apache License 2.0 5 votes vote down vote up
def _test():
    import doctest
    return doctest.testmod() 
Example 50
Project: ironpython2   Author: IronLanguages   File: doctest.py    License: Apache License 2.0 5 votes vote down vote up
def report_failure(self, out, test, example, got):
        raise DocTestFailure(test, example, got)

######################################################################
## 6. Test Functions
######################################################################
# These should be backwards compatible.

# For backward compatibility, a global instance of a DocTestRunner
# class, updated by testmod. 
Example 51
Project: ironpython2   Author: IronLanguages   File: doctest.py    License: Apache License 2.0 5 votes vote down vote up
def run_docstring_examples(f, globs, verbose=False, name="NoName",
                           compileflags=None, optionflags=0):
    """
    Test examples in the given object's docstring (`f`), using `globs`
    as globals.  Optional argument `name` is used in failure messages.
    If the optional argument `verbose` is true, then generate output
    even if there are no failures.

    `compileflags` gives the set of flags that should be used by the
    Python compiler when running the examples.  If not specified, then
    it will default to the set of future-import flags that apply to
    `globs`.

    Optional keyword arg `optionflags` specifies options for the
    testing and output.  See the documentation for `testmod` for more
    information.
    """
    # Find, parse, and run all tests in the given module.
    finder = DocTestFinder(verbose=verbose, recurse=False)
    runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
    for test in finder.find(f, name, globs=globs):
        runner.run(test, compileflags=compileflags)

######################################################################
## 7. Tester
######################################################################
# This is provided only for backwards compatibility.  It's not
# actually used in any way. 
Example 52
Project: ironpython2   Author: IronLanguages   File: test_zipimport_support.py    License: Apache License 2.0 5 votes vote down vote up
def test_doctest_main_issue4197(self):
        test_src = textwrap.dedent("""\
                    class Test:
                        ">>> 'line 2'"
                        pass

                    import doctest
                    doctest.testmod()
                    """)
        pattern = 'File "%s", line 2, in %s'
        with temp_dir() as d:
            script_name = make_script(d, 'script', test_src)
            exit_code, data = run_python(script_name)
            expected = pattern % (script_name, "__main__.Test")
            if verbose:
                print "Expected line", expected
                print "Got stdout:"
                print data
            self.assertIn(expected, data)
            zip_name, run_name = make_zip_script(d, "test_zip",
                                                script_name, '__main__.py')
            exit_code, data = run_python(zip_name)
            expected = pattern % (run_name, "__main__.Test")
            if verbose:
                print "Expected line", expected
                print "Got stdout:"
                print data
            self.assertIn(expected, data) 
Example 53
Project: ironpython2   Author: IronLanguages   File: test_doctest.py    License: Apache License 2.0 5 votes vote down vote up
def old_test4(): """
        >>> import types
        >>> m1 = types.ModuleType('_m1')
        >>> m2 = types.ModuleType('_m2')
        >>> test_data = \"""
        ... def _f():
        ...     '''>>> assert 1 == 1
        ...     '''
        ... def g():
        ...    '''>>> assert 2 != 1
        ...    '''
        ... class H:
        ...    '''>>> assert 2 > 1
        ...    '''
        ...    def bar(self):
        ...        '''>>> assert 1 < 2
        ...        '''
        ... \"""
        >>> exec test_data in m1.__dict__
        >>> exec test_data in m2.__dict__
        >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})

        Tests that objects outside m1 are excluded:

        >>> from doctest import Tester
        >>> t = Tester(globs={}, verbose=0)
        >>> t.rundict(m1.__dict__, "rundict_test", m1)  # f2 and g2 and h2 skipped
        TestResults(failed=0, attempted=4)

        Once more, not excluding stuff outside m1:

        >>> t = Tester(globs={}, verbose=0)
        >>> t.rundict(m1.__dict__, "rundict_test_pvt")  # None are skipped.
        TestResults(failed=0, attempted=8)

        The exclusion of objects from outside the designated module is
        meant to be invoked automagically by testmod.

        >>> doctest.testmod(m1, verbose=False)
        TestResults(failed=0, attempted=4)
""" 
Example 54
Project: ironpython2   Author: IronLanguages   File: pickletools.py    License: Apache License 2.0 5 votes vote down vote up
def _test():
    import doctest
    return doctest.testmod() 
Example 55
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: __init__.py    License: MIT License 5 votes vote down vote up
def _test():
    import doctest, os, sys
    sys.path.insert(0, os.pardir)
    import pytz
    return doctest.testmod(pytz) 
Example 56
Project: locality-sensitive-hashing   Author: singhj   File: dtcompat.py    License: MIT License 5 votes vote down vote up
def __init__(self, checker=None, verbose=None, optionflags=0):
        """
        Create a new test runner.

        Optional keyword arg `checker` is the `OutputChecker` that
        should be used to compare the expected outputs and actual
        outputs of doctest examples.

        Optional keyword arg 'verbose' prints lots of stuff if true,
        only failures if false; by default, it's true iff '-v' is in
        sys.argv.

        Optional argument `optionflags` can be used to control how the
        test runner compares expected output to actual output, and how
        it displays failures.  See the documentation for `testmod` for
        more information.
        """
        self._checker = checker or OutputChecker()
        if verbose is None:
            verbose = '-v' in sys.argv
        self._verbose = verbose
        self.optionflags = optionflags
        self.original_optionflags = optionflags

        # Keep track of the examples we've run.
        self.tries = 0
        self.failures = 0
        self._name2ft = {}

        # Create a fake output target for capturing doctest output.
        self._fakeout = _SpoofOut()

    #/////////////////////////////////////////////////////////////////
    # Reporting methods
    #///////////////////////////////////////////////////////////////// 
Example 57
Project: locality-sensitive-hashing   Author: singhj   File: dtcompat.py    License: MIT License 5 votes vote down vote up
def report_failure(self, out, test, example, got):
        raise DocTestFailure(test, example, got)

######################################################################
## 6. Test Functions
######################################################################
# These should be backwards compatible.

# For backward compatibility, a global instance of a DocTestRunner
# class, updated by testmod. 
Example 58
Project: locality-sensitive-hashing   Author: singhj   File: dtcompat.py    License: MIT License 5 votes vote down vote up
def run_docstring_examples(f, globs, verbose=False, name="NoName",
                           compileflags=None, optionflags=0):
    """
    Test examples in the given object's docstring (`f`), using `globs`
    as globals.  Optional argument `name` is used in failure messages.
    If the optional argument `verbose` is true, then generate output
    even if there are no failures.

    `compileflags` gives the set of flags that should be used by the
    Python compiler when running the examples.  If not specified, then
    it will default to the set of future-import flags that apply to
    `globs`.

    Optional keyword arg `optionflags` specifies options for the
    testing and output.  See the documentation for `testmod` for more
    information.
    """
    # Find, parse, and run all tests in the given module.
    finder = DocTestFinder(verbose=verbose, recurse=False)
    runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
    for test in finder.find(f, name, globs=globs):
        runner.run(test, compileflags=compileflags)

######################################################################
## 7. Tester
######################################################################
# This is provided only for backwards compatibility.  It's not
# actually used in any way. 
Example 59
Project: faces   Author: skarlekar   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _test():
    import doctest, os, sys
    sys.path.insert(0, os.pardir)
    import pytz
    return doctest.testmod(pytz) 
Example 60
Project: faces   Author: skarlekar   File: __init__.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _test():
    import doctest, os, sys
    sys.path.insert(0, os.pardir)
    import pytz
    return doctest.testmod(pytz)