def doctests(path):
    buf = StringIO()
    with(state(sys, stdout=buf)):
        doctest.testfile(path)
    res = buf.getvalue()
    if res != '':
        raise Exception(res)
예제 #2
0
def run(pattern):
    if pattern is None:
        testfiles = glob.glob('*.txt')
    else:
        testfiles = glob.glob(pattern)
    for file in testfiles: 
        doctest.testfile(file, extraglobs=EXTRA_GLOBALS)
예제 #3
0
def test():
    import doctest
    doctest.NORMALIZE_WHITESPACE = 1
    doctest.testfile("README.txt", verbose=1)

    #if __name__ == "__main__":
    """
예제 #4
0
def test_doctest_float_replacement(tmpdir):
    test1 = dedent("""
        This will demonstrate a doctest that fails due to a few extra decimal
        places::

            >>> 1.0 / 3.0
            0.333333333333333311
    """)

    test2 = dedent("""
        This is the same test, but it should pass with use of
        +FLOAT_CMP::

            >>> 1.0 / 3.0  # doctest: +FLOAT_CMP
            0.333333333333333311
    """)

    test1_rst = tmpdir.join('test1.rst')
    test2_rst = tmpdir.join('test2.rst')
    test1_rst.write(test1)
    test2_rst.write(test2)

    with pytest.raises(doctest.DocTestFailure):
        doctest.testfile(str(test1_rst), module_relative=False,
                         raise_on_error=True, verbose=False, encoding='utf-8')

    doctest.testfile(str(test2_rst), module_relative=False,
                     raise_on_error=True, verbose=False, encoding='utf-8')
예제 #5
0
def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "ht", ["help"])
        except getopt.error, msg:
            raise Usage(msg)
        
        for o, a in opts:
            if o == "-t":
                import doctest
                doctest.testfile("doctest.txt", globs={"key":APIKEY}) # pass dict with api-key to doctest
            elif o in ("-h", "--help"):
                print "..."
        if len(opts) == 0 and len(argv[1:]) == 1:
            filename = args[0]
            f = open(filename, 'r')
            txt = f.read()
            f.close()
                
            myapikey = APIKEY 
            zApi = ZemantaAPI(myapikey)
            result = zApi.extractEntities(txt, "ntriples")
            zApi.summary(result)
예제 #6
0
파일: test.py 프로젝트: k0s/jsgn
def run_tests():
    directory = os.path.dirname(os.path.abspath(__file__))
    extraglobs = {'here': directory}
    tests =  [ test for test in os.listdir(directory)
               if test.endswith('.txt') ]
    for test in tests:
        doctest.testfile(test, extraglobs=extraglobs)
예제 #7
0
    def run(self):
        '''
        Finds all the tests files in tests/, and run doctest on them.
        '''
        pymods = []
        pyxmods = []
        for root, dirs, files in os.walk('arboris'):
            for file in files:
                package = '.'.join(root.split(sep))
                if file.endswith('.py') and file != '__init__.py':
                    pymods.append('.'.join([package, splitext(file)[0]]))
                elif file.endswith('.so'):
                    pyxmods.append('.'.join([package, splitext(file)[0]]))

        for mod in pymods:
            exec('import {0} as module'.format(mod))
            doctest.testmod(module)

        for mod in pyxmods:
            exec('import {0} as mod'.format(mod))
            fix_module_doctests(mod)
            doctest.testmod(mod)

        for rst in glob(pjoin('tests', '*.rst')):
            doctest.testfile(rst)
예제 #8
0
파일: spyder.py 프로젝트: ww9rivers/c9r
def main():
    app = Main()
    if app.dryrun:
        import doctest
        doctest.testfile('test/spyder.text')
        exit(0)
    app()
예제 #9
0
def run(pattern):
    if pattern is None:
        testfiles = glob.glob("*.txt")
    else:
        testfiles = glob.glob(pattern)
    for file in testfiles:
        doctest.testfile(file)
예제 #10
0
def do_tests():
    here = os.path.dirname(__file__)
    for fn in os.listdir(here):
        if fn.endswith('.txt'):
            doctest.testfile(fn, optionflags=
                             doctest.ELLIPSIS
                             | doctest.REPORT_ONLY_FIRST_FAILURE)
예제 #11
0
 def doDoctestFile(self, module):
     log = []
     old_master, doctest.master = doctest.master, None
     try:
         doctest.testfile("xyz.txt", package=module, module_relative=True, globs=locals())
     finally:
         doctest.master = old_master
     self.assertEqual(log, [True])
예제 #12
0
파일: gist02.py 프로젝트: ajlopez/PLangRe
def test():
    
    
    for i in os.listdir("/home/mhmt/Belgeler"):
        if i.endswith(".py"):
            if i not in liste:
               doctest.testfile(i)
               liste.append(i)
예제 #13
0
def test(verbose=None):
    r"""
    Run all the doctests available.
    """
    import doctest
    import skfmm
    doctest.testmod(skfmm, verbose=verbose)
    doctest.testfile("heap.py")
예제 #14
0
def doctests(path):
    buf = StringIO()
    with state(sys, stdout=buf):
        doctest.testfile(path)
    res = buf.getvalue()
    if res != '':
        # import ipdb; ipdb.set_trace()
        raise Exception(res)
def _test():
    """tests current module"""
    import doctest
    logging.basicConfig(level=logging.DEBUG)
    doctest.testmod()
    testfilesdir = '../../Tests/SeqIO/'
    testfilesdir = './'
    doctest.testfile(testfilesdir + 'test_fastPhaseOutputIO.py')
예제 #16
0
def runTests():
	print('usage: '+sys.argv[0]+' [board size]')
	import platform
	print('python version '+platform.python_version())
	print('running unit tests...')
	import doctest
	doctest.testfile('CreateQueensTests.txt')
	print('done.')
예제 #17
0
파일: base.py 프로젝트: mmikic/ovpinf
def run_doctests(fname_list):
    assert isinstance(fname_list, (list, tuple)), "invalid input type %s for %r" % (type(fname_list), fname_list)
    for fname in fname_list:
        fname_abs = os.path.join("..", "tests", fname)
        if not os.path.exists(fname_abs):
            print "%s: Not found, skipping" % fname_abs
            continue
        print "%s: running doctests" % fname_abs
        doctest.testfile(fname_abs)
예제 #18
0
 def test_readme(self):
     try:
         original = sys.argv
         sys.argv = ['']
         doctest.testfile('../README.rst')
     finally:
         sys.argv = original
         for collector in begin.subcommands.COLLECTORS.values():
             collector.clear()
예제 #19
0
def main():
    for name in sys.argv[1:]:
        name = os.path.join(name)
        if name.startswith('-'):
            continue
        options = doctest.ELLIPSIS
        if '-u' in sys.argv:
            options = options | doctest.REPORT_UDIFF
        doctest.testfile(name, optionflags=options)
예제 #20
0
def runTests():
    print('usage: '+sys.argv[0]+' [board size] or')
    print('       '+sys.argv[0]+' [width] [height]')
    import platform
    print('python version '+platform.python_version())
    print('running unit tests...')
    import doctest
    doctest.testfile('CreateYpentominoTests.txt')
    print('done.')
예제 #21
0
def _test():
    import doctest, base, tests, icalendar, __init__, re
    flags = doctest.NORMALIZE_WHITESPACE | doctest.REPORT_UDIFF \
            | doctest.REPORT_ONLY_FIRST_FAILURE
    for mod in base, tests, icalendar, __init__:
        doctest.testmod(mod, verbose=0, optionflags=flags)
    try:
        doctest.testfile('../../README.txt', optionflags=flags)
    except IOError: #allow this test to fail if we can't find README.txt
        pass
예제 #22
0
파일: make.py 프로젝트: 0xsKu/500lines
def chapter_doctests(path):
    read_text_file(path)
    doctest.testfile(
        path,
        module_relative=False,
        optionflags=doctest.ELLIPSIS,
        )

    with project.cache_off():
        for dot in glob('*.dot'):
            read_text_file(dot)
예제 #23
0
파일: logfiler.py 프로젝트: ww9rivers/c9r
def main():
    '''
    '''
    app = Main()
    if app.dryrun and os.access('test/logfiler.txt', os.R_OK):
        logger.debug('Configuration tested OK. Running more module tests.')
        import doctest
        doctest.testfile('test/logfiler.txt')
    else:
        app()
    exit(0)
예제 #24
0
파일: csvfix.py 프로젝트: ww9rivers/c9r
def main():
    '''
    '''
    fixr = CSVFixer()
    if fixr.dryrun and os.access('test/csvfix.txt', os.R_OK):
        fixr.log_debug('Configuration tested OK. Running more module tests.')
        import doctest
        doctest.testfile('test/csvfix.txt')
    else:
        fixr()
    exit(0)
예제 #25
0
def test_doc():
    # prepare for doctest
    os.mkdir("./test_hgapi")
    with open("test_hgapi/file.txt", "w") as target:
        target.write("stuff")
    try:
        # run doctest
        doctest.testfile("../README.rst")
    finally:
        # cleanup
        shutil.rmtree("test_hgapi")
    def do_quit(self, args):
        """
        :method: quit or q
        :description: Quit the application. Will prompt the user as to
        whether the user would like to save the data serialised.
        :param: self
        :return: Will exit the app.
        """
        doctest.testfile("doctests.txt")

        print('Quitting...')
        raise SystemExit
예제 #27
0
파일: full.py 프로젝트: t-larsen/pytils
def run(path='./', verbose='-q'):
    """Perform full doctest of all relevant .py and .dt files.

    The function performs a doctest of all .py and .dt files located
    in or below either a specified directory or the working directory,
    and it either does so in quiet ('-q') or detailed ('-v') verbose
    level. In '-q' mode only failed tests are listed whereas all
    test details are provided in '-v' mode.

    Args:
        *path* (str): Path of the source directory for which to search
        for doctest containing .py and .dt files. All directories
        below *path* are also searched. If necessary, path segments
        should be separated by '/' and no absolute path should be
        used (i.e. the path may not begin with '/').

        *verbose* (str): Verbose level where '-v' indicates detailed
        test information is printed, and '-q' means quiet mode where
        only failed tests are reported.

    Returns:
        Nothing.

    Raises:
        ValueError if the specified directory does not exist.
        ValueError if verbose level is incorrectly specified.

    """
    # Determine path and verbose level
    if not os.path.isdir(path):
        raise ValueError('Specified directory does not exist.')
    if not verbose in ('-v', '-q'):
        raise ValueError('Verbose level incorrectly specified.')

    # Files not included in the test
    OMIT_FILES = ('full.py', '__init__.py')

    # Perform test
    print('{0}'.format(78*'-'))
    for (dirpath, dirnames, filenames) in os.walk(path):
        for filename in filenames:
            # Extract filename extension
            ext_name = os.path.splitext(filename)[1][1:].strip().lower()

            # Perform doctest for all relevant .py and .dt files
            go = filename not in OMIT_FILES
            if ext_name in ('py', 'dt') and go:
                full_filename = os.sep.join([dirpath, filename])
                disp_str = "Test-file:   {0}".format(full_filename)
                print("{0}\n".format(disp_str))
                doctest.testfile(full_filename, module_relative=False)
                print('{0}'.format(78*'-'))
예제 #28
0
파일: rsync.py 프로젝트: ww9rivers/c9r
def main():
    '''Initiate a NetMap run. Exit if dry-run option is given without running the jobs.

    Must have this main() function for this to be run from another
    python program in a child process.
    '''
    app = RsyncApp()
    if app.dryrun:
        import doctest
        doctest.testfile('test/rsync.text')
    app.exit_dryrun()
    for job, result in app().iteritems():
        logger.info('Result of rsync job "{0}" = {status}, [ {out} ] ({err})'.format(job, **result))
예제 #29
0
 def test_run_doctest(self):
     class DummyStream:
         content = ""
         def write(self, text):
             self.content += text
     dummy_stream = DummyStream()
     import sys
     before = sys.stdout
     sys.stdout = dummy_stream
     import doctest
     doctest.testfile('doctests.txt')
     sys.stdout = before
     self.assertEqual(dummy_stream.content, "")
예제 #30
0
def main():
    data = open('README.rst').read()
    write_all(data)
    new_data = fo.getvalue()
    fo.close()

    if new_data == data:
        print "already up-to-date"
    else:
        with open('README.rst', 'w') as f:
            f.write(new_data)

    doctest.testfile('README.rst')
예제 #31
0
def test():
    import doctest
    doctest.NORMALIZE_WHITESPACE = 1
    doctest.testfile("README.txt", verbose=1)
#!/usr/bin/python3
"""This is "0-add_integer" module.
This function takes to integer or floats and add
them together. exemple:
>>> add_integer(1, 4)
5
"""


def add_integer(a, b=98):
    """function to add integer"""
    if type(a) != int and type(a) != float:
        raise TypeError("a must be an integer")
    if type(b) != float and type(b) != int:
        raise TypeError("b must be an integer")
    else:
        return int(a) + int(b)


if __name__ == "__main__":
    import doctest
    doctest.testfile("tests/0-add_integer.txt")
예제 #33
0
     if item.find(".v") != -1:
         filename = item
 xz_flag = False
 test_number = 100
 all_mode = False
 random_mode = False
 deductive_mode = False
 time_mode = False
 time_slot = 0
 upper_args = list(map(str.upper, args))
 if len(upper_args) == 1:
     help_func()
     sys.exit()
 if "TEST" in upper_args:
     doctest.testfile("test.py",
                      optionflags=doctest.NORMALIZE_WHITESPACE
                      | doctest.ELLIPSIS,
                      verbose=True)
     sys.exit()
 if "INPUT" in upper_args:
     index = upper_args.index("INPUT")
     if len(upper_args) > index + 1:
         input_data = list(map(map_int, list(args[index + 1].split(","))))
 if "XZ" in upper_args:
     xz_flag = True
 if "RANDOM" in upper_args and (len(upper_args) > 2):
     random_mode = True
     all_mode = True
     index = upper_args.index("RANDOM")
     try:
         if len(upper_args) > index + 1:
             test_number = int(args[index + 1])
예제 #34
0
    skip.add("segfault-27.txt")
    skip.add("segfault-35.txt")
    skip.add("vertex_denom-37.txt")
    skip.add("modify_cone_renf.txt")

# run doctests
attempted = failed = 0
for filename in os.listdir(os.curdir):
    if filename.endswith('.txt'):
        if filename in skip:
            print("Skip {}".format(filename))
            continue

        print("Doctest {}".format(filename))
        result = doctest.testfile(filename,
                                  optionflags=doctest.IGNORE_EXCEPTION_DETAIL
                                  | doctest.NORMALIZE_WHITESPACE
                                  | doctest.REPORT_NDIFF)
        print("  {} tests".format(result[1]))
        if result[0]:
            print("  {} FAILURES".format(result[0]))
        failed += result[0]
        attempted += result[1]

# unit tests
from generic_test import tests

for test in tests:
    test(verbosity=2).run(repeat=10)

sys.exit(failed)
예제 #35
0
def test():
    import doctest

    doctest.testfile("iso2709_test.txt")
import glob
import doctest

result = doctest.testfile('__grade__.txt', report=False, verbose=False)
a, b = result
print('\n>>>>  ', result, ' <<<<\n')
open('__grade__', 'w').write(str(round(float(b - a) / float(b) * 5.0, 1)))
예제 #37
0
            it will be written after a symbol writeHeader[1].
        """
        # get all table names
        tableNames = self.getAllTableNames()

        # write out table one by one
        for aTable in tableNames:
            # create a file with the correpsonding name
            with open(path.join(writeToFolder, aTable + ext),
                      "w") as tableFile:
                # write header
                if writeHeader[0]:
                    fieldNames = [
                        item[0] for item in self.getTableInfo(aTable)
                    ]
                    tableFile.write(writeHeader[1] + sep.join(fieldNames) +
                                    "\n")
                for aRecond in self.selectFromTable(aTable):
                    tableFile.write(sep.join(map(str, aRecond)) + "\n")

    class SqliteDBError(sqlite3.OperationalError):
        """
            General error exception encountered during database operations.
        """
        pass


if __name__ == '__main__':
    import doctest
    doctest.testfile("DBR_readme.txt")
#!/usr/bin/python3
"""Module add_integer"""


def add_integer(a, b=98):
    """add_integer.

    Args:
        a: Fisrt number.
        b: second number.

    Returns:
        the add of two numbers.

    """
    if not isinstance(a, (int, float)):
        raise TypeError('a must be an integer')
    elif not isinstance(b, (int, float)):
        raise TypeError('b must be an integer')
    else:
        return int(a) + int(b)


if __name__ == "__main__":
    import doctest
    doctest.testfile("test/0.add_integer.txt")
예제 #39
0
class Bin:
    """A location for storing BinItems."""
    def __init__(self, name):
        self.name = name
        self.contents = []

    def __str__(self):
        s = "Bin {0}:".format(self.name)
        for item in self.contents:
            s += '\n  ' + item.__str__()
        return s

    def add(self, item):
        for index, value in enumerate(self.contents):
            if value.sku == item.sku:
                value.quantity += item.quantity
                break
            if value.sku < item.sku:
                continue
            else:
                self.contents.insert(index, item)
                break
        else:
            self.contents.append(item)


if __name__ == '__main__':
    import doctest
    doctest.testfile("bin_tests.txt")
예제 #40
0
 def test_internal(self):
     tmpfile = self.adapt_rst('../../doc/INTERNAL.rst')
     failed, _ = doctest.testfile(tmpfile, False)
     self.assertEqual(failed, 0)
     os.remove(tmpfile)
예제 #41
0
 def test_cli(self):
     tmpfile = self.adapt_rst('../../doc/CLI.rst')
     failed, _ = doctest.testfile(tmpfile, False)
     self.assertEqual(failed, 0)
     os.remove(tmpfile)
예제 #42
0
 def test_tutorial(self):
     failed, _ = doctest.testfile('../../doc/TUTORIAL.rst')
     self.assertEqual(failed, 0)
예제 #43
0
def test_readme():
    failures, _ = doctest.testfile('../README.rst')

    if failures:
        raise Exception('doctests in README.rst failed')
예제 #44
0
        for i, j in enumerate(self.category[::-1]):
            if j.scheme == LABEL_SCHEME:
                del(self.category[ln-1-i])

    def clean_annotations(self):
        """Clear all annotations from an item. Useful for taking an item from
        another user's library/annotation feed and adding it to the 
        authenticated user's library without adopting annotations."""
        self.remove_label()
        self.review = None
        self.rating = None

    
    def get_google_id(self):
        """Get Google's ID of the item."""
        return self.id.text.split('/')[-1]


class BookFeed(_AtomFromString, gdata.GDataFeed):
    """Represents a feed of entries from a search."""

    _tag = 'feed'
    _namespace = atom.ATOM_NAMESPACE
    _children = gdata.GDataFeed._children.copy()
    _children['{%s}%s' % (Book._namespace, Book._tag)] = (Book._tag, [Book])


if __name__ == '__main__':
    import doctest
    doctest.testfile('datamodels.txt')
예제 #45
0
 def _test_can_doctest_readme(self):
     project_folder = os.path.dirname(_CsvTest._TEST_FOLDER)
     readme_path = os.path.join(project_folder, 'README.rst')
     doctest.testfile(readme_path, module_relative=False)
예제 #46
0
        slope = ((y2 - y1) / (x2 - x1))
        print('The slope is', slope, 'and the distance is', distance)


def numVowels(c):
    file = open(c)
    read1 = file.read()
    file.close
    read = read1.lower()
    count = 0
    vowels = ('aeiou')
    for letter in read:
        if letter in vowels:
            count += 1
    return count


def numLen(s, target):
    listlength = s.split()
    lator = 0
    for wordlength in listlength:
        wordlength1 = len(wordlength)
        if wordlength1 == target:
            lator += 1
    return lator


if __name__ == '__main__':
    import doctest
    print(doctest.testfile('hw4TEST.py'))
예제 #47
0
import doctest

print 'Before testing be sure to set your key in README.txt..\n\n'

doctest.testfile('README.rst')
예제 #48
0
파일: echo.py 프로젝트: novas0x2a/watchdog
        pass
    elif is_classmethod(method):
        setattr(klass, mname, classmethod(echo(method.im_func, write)))
    else:
        setattr(klass, mname, echo(method, write))


def echo_class(klass, write=sys.stdout.write):
    """ Echo calls to class methods and static functions
    """
    for _, method in inspect.getmembers(klass, inspect.ismethod):
        echo_instancemethod(klass, method, write)
    for _, fn in inspect.getmembers(klass, inspect.isfunction):
        setattr(klass, name(fn), staticmethod(echo(fn, write)))


def echo_module(mod, write=sys.stdout.write):
    """ Echo calls to functions and methods in a module.
    """
    for fname, fn in inspect.getmembers(mod, inspect.isfunction):
        setattr(mod, fname, echo(fn, write))
    for _, klass in inspect.getmembers(mod, inspect.isclass):
        echo_class(klass, write)


if __name__ == "__main__":
    import doctest
    optionflags = doctest.ELLIPSIS
    doctest.testfile('echoexample.txt', optionflags=optionflags)
    doctest.testmod(optionflags=optionflags)
        raise TypeError("div must be a number")
    if div == 0:
        raise ZeroDivisionError("division by zero")
    if not isinstance(matrix, list) or not matrix:
        raise TypeError("matrix must be a matrix (list of lists) " +
                        "of integers/floats")
    if not isinstance(matrix[0], list) or not matrix[0]:
        raise TypeError("matrix must be a matrix (list of lists) " +
                        "of integers/floats")

    size = len(matrix[0])
    matx = [[0 for j in range(size)] for i in range(len(matrix))]
    for i in range(len(matrix)):
        if type(matrix[i]) is not list:
            raise TypeError("matrix must be a matrix (list of lists) " +
                            "of integers/floats")
        if size != len(matrix[i]):
            raise TypeError("Each row of the matrix must have the same size")
        for j in range(len(matrix[i])):
            if type(matrix[i][j]) not in [int, float]:
                raise TypeError("matrix must be a matrix (list of lists) " +
                                "of integers/floats")
            matx[i][j] = matrix[i][j] / div
            matx[i][j] = round(matx[i][j], 2)

    return matx

if __name__ == "__main__":
    import doctest
    doctest.testfile("tests/2-matrix_divided.txt")
예제 #50
0
    def dtest(self, event):
        """The handler for dtest
        """

        import leo.core.leoGlobals as g

        # get a valid temporary filename
        createfile, tempfilename = g.create_temp_file()
        createfile.close()

        selected = False

        # if text is selected, only test selection
        if self.c.frame.body.hasTextSelection():
            selected = True
            selection = self.c.frame.body.getSelectedText()
            tempfile = open(tempfilename, 'w')
            tempfile.write(selection)
            tempfile.close()

        # if no selection, test this subtree
        else:
            self.c.importCommands.flattenOutline(tempfilename)

        tempfile = open(tempfilename)
        text = tempfile.readlines()
        tempfile.close()
        # strip trailing whitespace, an annoying source of doctest failures
        text = [line.rstrip() for line in text]
        text = "\n".join(text)
        tempfile = open(tempfilename, 'w')
        tempfile.write(text)
        tempfile.close()

        import copy

        # build globals dictionary
        globals = {'c': copy.copy(self.c), 'g': g}

        # run doctest on temporary file
        failures, tests = doctest.testfile(tempfilename,
                                           module_relative=False,
                                           optionflags=doctest.ELLIPSIS,
                                           globs=globals)

        #@+<<report summary of results>>
        #@+node:ekr.20070119094733.10: *4* <<report summary of results>>
        if selected:
            g.es('Result of running doctest on selected text;')
        else:
            g.es('Result of running doctest on this subtree;')
        if failures == 0:
            g.blue("%s tests run successfully" % tests)
        if failures == 1:
            g.error("There was one failure in %s tests" % tests)
        if failures > 1:
            g.error("%s failures in %s tests" % (failures, tests))
        #@-<<report summary of results>>

        #clean up temp file
        os.remove(tempfilename)
예제 #51
0
파일: Trim.py 프로젝트: ww9rivers/c9r
#! /usr/bin/env python3

from c9r.util.filter import Filter


class Trim(Filter):
    ''' Filter to trim extra spaces in (before and after) a string.
    '''
    def write(self, data):
        '''Normalize given data before writing to the pipe.

        /data/ is expected to be a dictionary-type object, with.
        '''
        for xk, xv in data.items():
            data[xk] = xv.strip()
        return Filter.write(self, data)


if __name__ == '__main__':
    import doctest
    doctest.testfile('test/Trim.test')
예제 #52
0
    0.0.1 | 20-APR-2014 : * Initial version.
    0.0.2 | 08-MAY-2014 : * Introduced omit_files tuple including files not to
                            be included in the test.
License:
    BSD 2-Clause
    
"""

import os
import doctest

# Files not included in the test
omit_files = ('run_full_doctest.py', 'run_single_doctest.py', '__init__.py')

# Perform test
path = '.'
print('{0}'.format(78 * '='))
for (dirpath, dirnames, filenames) in os.walk(path):
    for filename in filenames:
        # Extract filename extension
        ext_name = os.path.splitext(filename)[1][1:].strip().lower()

        # Perform doctest for all relevant .py and .dt files
        go = filename not in omit_files
        if ext_name in ('py', 'dt') and go:
            full_filename = os.sep.join([dirpath, filename])
            disp_str = "File under doctest:   {0}".format(filename)
            print("{0}\n{1}".format(disp_str, len(disp_str) * '-'))
            doctest.testfile(full_filename)
            print('{0}'.format(78 * '='))
예제 #53
0
 def test__readme_file(self):
     readme_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "README.rst"))
     self.assertTrue(os.path.exists(readme_path))
     result = doctest.testfile(readme_path, module_relative=False)
     self.assertEqual(result.failed, 0, "%s tests failed!" % result.failed)
예제 #54
0
def run_bsm1_readme():
    from exposan import bsm1 as b1
    b1.bsm1.reset_cache()
    readme = os.path.join(b1.bsm1_path, 'README.rst')
    testfile(readme, module_relative=False)
    del b1
예제 #55
0
    for i in range(number_of_files):
        print("Generating {0} from {1}".format(i + 1, number_of_files))
        file_name_temp = file_name
        if number_of_files > 1:
            file_name_temp = file_name + "_" + str(i + 1)
        gen_graph(input_dict, file_name_temp)
        line(40)


if __name__ == "__main__":
    tprint("Pyrgg", "larry3d")
    tprint("v" + PYRGG_VERSION)
    description_print()
    args = sys.argv
    if len(args) > 1:
        if args[1].upper() == "TEST":
            error_flag = doctest.testfile("test.py", verbose=False)[0]
            sys.exit(error_flag)
        else:
            print("Bad Input!")
            print("Test (Run doctest)")
            print("Without arg --> Normal Run")
    else:
        EXIT_FLAG = False
        while not EXIT_FLAG:
            run()
            INPUTINDEX = str(
                input("Press [R] to restart Pyrgg or any other key to exit."))
            if INPUTINDEX.upper() != "R":
                EXIT_FLAG = True
예제 #56
0
            return formatted_coord

        ### relations
    def __eq__(self, other):
        return self.spec == other.spec

    def __ge__(self, other):
        return self.spec >= other.spec

    def __gt__(self, other):
        return self.spec > other.spec

    def __le__(self, other):
        return self.spec <= other.spec

    def __lt__(self, other):
        return self.spec < other.spec

    def __ne__(self, other):
        return self.spec != other.spec

    ### other
    @classmethod
    def _print_error_message(cls, method_name, message):
        print '%s.%s: %s' % (cls.__name__, method_name, message)


if __name__ == '__main__':
    import doctest
    doctest.testfile('tests/point_test.txt')
예제 #57
0
#!/usr/bin/python3
"""function that prints a square with the character #.

"""


def print_square(size):
    """function that prints a square with the character #
    arg: int or float
    return: noting
    """
    if type(size) != int:
        raise TypeError('size must be an integer')
    if size < 0:
        raise ValueError('size must be >= 0')
    if size < 0 and type(size) is float:
        raise TypeError('size must be an integer')
    if size is None:
        raise TypeError('size must be an integer')
    for i in range(size):
        for j in range(size):
            if j is size - 1:
                print('#')
            else:
                print('#', end='')


if __name__ == '__main__':
    import doctest
    doctest.testfile(4 - print_square)
예제 #58
0
    # output --> [('flour', 10), ('sugar', 30)]

    # CLASS METHODS:
    @classmethod
    def get(cls, name):
        if name not in cls.cache:
            print("Sorry, that cupcake doesn't exist")

        else:
            return cls.cache[name]

    def __repr__(self):
        """Human-readable printout for debugging."""
        # test_cupcake.name = "testing 123"
        # test_cupcake.qty = 0
        # test_cupcake.flavor = "vanilla"
        # test_price = 1.00

        return f'<Cupcake name="{self.name}" qty={self.qty}>'


if __name__ == "__main__":
    import doctest

    result = doctest.testfile(
        "doctests.py", report=False, optionflags=(doctest.REPORT_ONLY_FIRST_FAILURE)
    )
    doctest.master.summarize(1)
    if result.failed == 0:
        print("ALL TESTS PASSED")
예제 #59
0
def print_square(size):
    """ Function to pritn a square
    Args:
        size: int
    Returns:
        None

    >>> print_square(3)
    ###
    ###
    ###

    """

    if type(size) is not int:
        raise TypeError("size must be an integer")
    if size < 0:
        if type(size) is float:
            raise TypeError("size must be an integer")
        raise ValueError("size must be >= 0")
    for i in range(size):
        print("{}".format("#" * size))
        if i == size:
            break


if __name__ == "__main__":
    import doctest
    doctest.testfile("tests/4-print_square.txt")
예제 #60
0
#!/usr/bin/python3
"""
Test Driven Doc import
Don't import using __import__
"""

if __name__ == "__main__":
    import doctest
    doctest.testfile("tests/5-text_indentation.txt")


def text_indentation(text):
    """
    function that prints a text with 2 new lines after each of
    these characters: . ? and :
    Args:
    text: text to indent
    """
    if type(text) is not str:
        raise TypeError("text must be a string")
    space = 0
    for a in text:
        if space == 0:
            if a == ' ':
                continue
            else:
                space = 1
        if space == 1:
            if a == '?' or a == ':':
                print(a)
                print()