Example #1
0
    def gen_snippets(self, docname, doctree):
        code = []
        for node in doctree.traverse(condition):
            source = 'test' in node and node['test'] or node.astext()
            try:
                example = doctest.script_from_examples(source)
            except Exception as exc:
                # catch doctest errors
                self.info('\nDocument: %s\n----------%s\n' %
                          (docname, '-'*len(docname)))
                raise Exception(exc)
            
            if self.config.codesnippet_strip_doctest_directives:
                # remove doctest directives
                lines = (re.split(r'\s*#\s*doctest:', line, 1)[0]
                         for line in example.split('\n'))
                example = '\n'.join(lines)

            code.append(example)

        if len(code) > 0:
            self.info('\nDocument: %s\n----------%s\n' %
                      (docname, '-'*len(docname)))
            self.write_code(docname, code)
            self.write_rst(docname)
def run_examples(shell, examples):
    '''run doctest examples as if typed in shell.
    >>> if globals().get('shell'):
    ...     run_examples(shell, run_examples.__doc__, trace_code = False)
    '''
    import doctest
    script = doctest.script_from_examples(examples)
    run_snippet(shell, script)
def debug_examples(shell, examples, trace_code = True):
    '''Debug doctest examples as if typed in shell.
    >>> if globals().get('shell'):
    ...     debug_examples(shell, debug_examples.__doc__, trace_code = False)
    '''
    import doctest
    script = doctest.script_from_examples(examples)
    debug_snippet(shell, script, trace_code=trace_code)
Example #4
0
    def gen_snippets(self, docname, doctree):
        code = []
        for node in doctree.traverse(condition):
            source = node.has_key("test") and node["test"] or node.astext()
            try:
                example = doctest.script_from_examples(source)
            except Exception, exc:
                # catch doctest errors
                self.info("\nDocument: %s\n----------%s\n" % (docname, "-" * len(docname)))
                raise Exception(exc)

            if self.config.codesnippet_strip_doctest_directives:
                # remove doctest directives
                lines = (re.split(r"\s*#\s*doctest:", line, 1)[0] for line in example.split("\n"))
                example = "\n".join(lines)

            code.append(example)
def inline_examples(examples_text, 
        locals_dict, globals_dict, 
        verify_examples = True):
    r'''Run examples as if in this context.
    Useful to inspect regression and construct by example.
    No output is shown when running.
    >>> def f(x):  '>>> ___a = 1'
    >>> inline_examples(f.__doc__, locals(), globals())
    >>> ___a
    1
    >>> del ___a

    #>>> inline_examples(inline_examples.__doc__, 
    #...     locals(), globals())

    Notify if example is incosistent and do not run.
    >>> def g():  
    ...     """An inconsistent example.
    ...     >>> ___b = 2
    ...     >>> ___b
    ...     1
    ...     """
    >>> inline_examples(g.__doc__, locals(), globals()) # doctest: +ELLIPSIS
    ****************...
    File "...code_unit.py", line 3, in An inconsistent example.
    Failed example:
        ___b
    Expected:
        1
    Got:
        2
    '''
    failures = 0
    if verify_examples:
        failures, tests = test_example(examples_text, 
                globals_dict)
    if 0 == failures:
        save_stdout = sys.stdout
        sys.stdout = null_output_class()
        script = doctest.script_from_examples(examples_text)
        exec(script, locals_dict, globals_dict)
        sys.stdout = save_stdout
Example #6
0
def execButNoTest(name='__main__'):
    module = sys.modules.get(name)
    
    # the syntax of doctest changed substantially between Python 2.3 and 2.4
    # <http://sourceforge.net/tracker/index.php?func=detail&aid=1120348&group_id=118428&atid=681141>
    if sys.version_info >= (2, 4):
        tests = doctest.DocTestFinder().find(module)
        tests = [doctest.script_from_examples(t.docstring) for t in tests]
        
        # Python 2.4 returns comments, too, and doesn't always end in a \n,
        # which chokes exec/compile. Arguably a bug in Python.
        # <http://sourceforge.net/tracker/index.php?func=detail&aid=1172785&group_id=5470&atid=105470>
        tests = [t + '\n' for t in tests]
    else:
        tests = [doc for (dummy, doc, dummy, dummy) in doctest._find_tests(module, "")]
        tests = [doctest._extract_examples(t) for t in tests]
	tests = ["\n".join([source for source, expect, dummy in t]) for t in tests]

    if not tests:
        raise ValueError("no tests found")

    for t in tests:
        exec t
Example #7
0
 def invoke_debugger(self, event=None):
     '''
     Start an external debugger in another process to debug a script. The
     script is the presently selected text or then entire tree's script.
     '''
     c, p = self.c, self.c.p
     python = sys.executable
     script = g.getScript(c, p)
     winpdb = self.findDebugger()
     if not winpdb: return
     #check for doctest examples
     try:
         import doctest
         parser = doctest.DocTestParser()
         examples = parser.get_examples(script)
         # if this is doctest, extract the examples as a script
         if len(examples) > 0:
             script = doctest.script_from_examples(script)
     except ImportError:
         pass
     # Special case: debug code may include g.es("info string").
     # insert code fragment to make this expression legal outside Leo.
     hide_ges = "class G:\n def es(s,c=None):\n  pass\ng = G()\n"
     script = hide_ges + script
     # Create a temp file from the presently selected node.
     filename = c.writeScriptFile(script)
     if not filename:
         return
     # Invoke the debugger, retaining the present environment.
     os.chdir(g.app.loadDir)
     if False and subprocess:
         cmdline = '%s %s -t %s' % (python, winpdb, filename)
         subprocess.Popen(cmdline)
     else:
         args = [sys.executable, winpdb, '-t', filename]
         os.spawnv(os.P_NOWAIT, python, args)
def run(arguments, content, options, state_machine, state, lineno):
    document = state_machine.document
    config = document.settings.env.config
    nofigs = 'nofigs' in options

    formats = get_plot_formats(config)
    default_fmt = formats[0][0]

    options.setdefault('include-source', config.plot_include_source)
    if 'class' in options:
        # classes are parsed into a list of string, and output by simply
        # printing the list, abusing the fact that RST guarantees to strip
        # non-conforming characters
        options['class'] = ['plot-directive'] + options['class']
    else:
        options.setdefault('class', ['plot-directive'])
    keep_context = 'context' in options
    context_opt = None if not keep_context else options['context']

    rst_file = document.attributes['source']
    rst_dir = os.path.dirname(rst_file)

    if len(arguments):
        if not config.plot_basedir:
            source_file_name = os.path.join(setup.app.builder.srcdir,
                                            directives.uri(arguments[0]))
        else:
            source_file_name = os.path.join(setup.confdir, config.plot_basedir,
                                            directives.uri(arguments[0]))

        # If there is content, it will be passed as a caption.
        caption = '\n'.join(content)

        # Enforce unambiguous use of captions.
        if "caption" in options:
            if caption:
                raise ValueError(
                    'Caption specified in both content and options.'
                    ' Please remove ambiguity.')
            # Use caption option
            caption = options["caption"]

        # If the optional function name is provided, use it
        if len(arguments) == 2:
            function_name = arguments[1]
        else:
            function_name = None

        code = Path(source_file_name).read_text(encoding='utf-8')
        output_base = os.path.basename(source_file_name)
    else:
        source_file_name = rst_file
        code = textwrap.dedent("\n".join(map(str, content)))
        counter = document.attributes.get('_plot_counter', 0) + 1
        document.attributes['_plot_counter'] = counter
        base, ext = os.path.splitext(os.path.basename(source_file_name))
        output_base = '%s-%d.py' % (base, counter)
        function_name = None
        caption = options.get('caption', '')

    base, source_ext = os.path.splitext(output_base)
    if source_ext in ('.py', '.rst', '.txt'):
        output_base = base
    else:
        source_ext = ''

    # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames
    output_base = output_base.replace('.', '-')

    # is it in doctest format?
    is_doctest = contains_doctest(code)
    if 'format' in options:
        if options['format'] == 'python':
            is_doctest = False
        else:
            is_doctest = True

    # determine output directory name fragment
    source_rel_name = relpath(source_file_name, setup.confdir)
    source_rel_dir = os.path.dirname(source_rel_name).lstrip(os.path.sep)

    # build_dir: where to place output files (temporarily)
    build_dir = os.path.join(os.path.dirname(setup.app.doctreedir),
                             'plot_directive', source_rel_dir)
    # get rid of .. in paths, also changes pathsep
    # see note in Python docs for warning about symbolic links on Windows.
    # need to compare source and dest paths at end
    build_dir = os.path.normpath(build_dir)
    os.makedirs(build_dir, exist_ok=True)

    # output_dir: final location in the builder's directory
    dest_dir = os.path.abspath(
        os.path.join(setup.app.builder.outdir, source_rel_dir))
    os.makedirs(dest_dir, exist_ok=True)

    # how to link to files from the RST file
    dest_dir_link = os.path.join(relpath(setup.confdir, rst_dir),
                                 source_rel_dir).replace(os.path.sep, '/')
    try:
        build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/')
    except ValueError:
        # on Windows, relpath raises ValueError when path and start are on
        # different mounts/drives
        build_dir_link = build_dir
    source_link = dest_dir_link + '/' + output_base + source_ext

    # get list of included rst files so that the output is updated when any
    # plots in the included files change. These attributes are modified by the
    # include directive (see the docutils.parsers.rst.directives.misc module).
    try:
        source_file_includes = [
            os.path.join(os.getcwd(), t[0]) for t in state.document.include_log
        ]
    except AttributeError:
        # the document.include_log attribute only exists in docutils >=0.17,
        # before that we need to inspect the state machine
        possible_sources = {
            os.path.join(setup.confdir, t[0])
            for t in state_machine.input_lines.items
        }
        source_file_includes = [
            f for f in possible_sources if os.path.isfile(f)
        ]
    # remove the source file itself from the includes
    try:
        source_file_includes.remove(source_file_name)
    except ValueError:
        pass

    # make figures
    try:
        results = render_figures(code,
                                 source_file_name,
                                 build_dir,
                                 output_base,
                                 keep_context,
                                 function_name,
                                 config,
                                 context_reset=context_opt == 'reset',
                                 close_figs=context_opt == 'close-figs',
                                 code_includes=source_file_includes)
        errors = []
    except PlotError as err:
        reporter = state.memo.reporter
        sm = reporter.system_message(
            2,
            "Exception occurred in plotting {}\n from {}:\n{}".format(
                output_base, source_file_name, err),
            line=lineno)
        results = [(code, [])]
        errors = [sm]

    # Properly indent the caption
    caption = '\n' + '\n'.join('      ' + line.strip()
                               for line in caption.split('\n'))

    # generate output restructuredtext
    total_lines = []
    for j, (code_piece, images) in enumerate(results):
        if options['include-source']:
            if is_doctest:
                lines = ['', *code_piece.splitlines()]
            else:
                lines = [
                    '.. code-block:: python', '',
                    *textwrap.indent(code_piece, '    ').splitlines()
                ]
            source_code = "\n".join(lines)
        else:
            source_code = ""

        if nofigs:
            images = []

        opts = [
            ':%s: %s' % (key, val) for key, val in options.items()
            if key in ('alt', 'height', 'width', 'scale', 'align', 'class')
        ]

        # Not-None src_link signals the need for a source link in the generated
        # html
        if j == 0 and config.plot_html_show_source_link:
            src_link = source_link
        else:
            src_link = None

        result = jinja2.Template(config.plot_template or TEMPLATE).render(
            default_fmt=default_fmt,
            dest_dir=dest_dir_link,
            build_dir=build_dir_link,
            source_link=src_link,
            multi_image=len(images) > 1,
            options=opts,
            images=images,
            source_code=source_code,
            html_show_formats=config.plot_html_show_formats and len(images),
            caption=caption)

        total_lines.extend(result.split("\n"))
        total_lines.extend("\n")

    if total_lines:
        state_machine.insert_input(total_lines, source=source_file_name)

    # copy image files to builder's output directory, if necessary
    Path(dest_dir).mkdir(parents=True, exist_ok=True)

    for code_piece, images in results:
        for img in images:
            for fn in img.filenames():
                destimg = os.path.join(dest_dir, os.path.basename(fn))
                if fn != destimg:
                    shutil.copyfile(fn, destimg)

    # copy script (if necessary)
    if config.plot_html_show_source_link:
        Path(dest_dir, output_base + source_ext).write_text(
            doctest.script_from_examples(code)
            if source_file_name == rst_file and is_doctest else code,
            encoding='utf-8')

    return errors
Example #9
0
                    entry.move,
                ]
            pv[pos] = entry.move
            pos = pos.move(entry.move)
        return list(pv.values())


enginedict = OrderedDict(
    Sunfish=Sunfish,
    Fool=Fool,
    Minimax=Minimax,
    Negamax=Negamax,
    AlphaBeta=AlphaBeta,
)

if __name__ == '__main__':

    import sys, os
    import doctest

    docscript = lambda obj=None: doctest.script_from_examples(
        __doc__ if obj is None else getattr(obj, '__doc__'))

    if sys.argv[0] == "":  # if the python session is inside an emacs buffer
        print(doctest.testmod(optionflags=doctest.REPORT_ONLY_FIRST_FAILURE))
    else:
        if len(sys.argv) == 3:
            white = enginedict[sys.argv[1]]()
            black = enginedict[sys.argv[2]]()
            p = play(white, black)
def render_figures(code,
                   code_path,
                   output_dir,
                   output_base,
                   context,
                   function_name,
                   config,
                   context_reset=False,
                   close_figs=False,
                   code_includes=None):
    """
    Run a pyplot script and save the images in *output_dir*.

    Save the images under *output_dir* with file names derived from
    *output_base*
    """
    formats = get_plot_formats(config)

    # Try to determine if all images already exist

    is_doctest, code_pieces = _split_code_at_show(code)

    # Look for single-figure output files first
    all_exists = True
    img = ImageFile(output_base, output_dir)
    for format, dpi in formats:
        if context or out_of_date(
                code_path, img.filename(format), includes=code_includes):
            all_exists = False
            break
        img.formats.append(format)

    if all_exists:
        return [(code, [img])]

    # Then look for multi-figure output files
    results = []
    all_exists = True
    for i, code_piece in enumerate(code_pieces):
        images = []
        for j in itertools.count():
            if len(code_pieces) > 1:
                img = ImageFile('%s_%02d_%02d' % (output_base, i, j),
                                output_dir)
            else:
                img = ImageFile('%s_%02d' % (output_base, j), output_dir)
            for fmt, dpi in formats:
                if context or out_of_date(
                        code_path, img.filename(fmt), includes=code_includes):
                    all_exists = False
                    break
                img.formats.append(fmt)

            # assume that if we have one, we have them all
            if not all_exists:
                all_exists = (j > 0)
                break
            images.append(img)
        if not all_exists:
            break
        results.append((code_piece, images))

    if all_exists:
        return results

    # We didn't find the files, so build them

    results = []
    ns = plot_context if context else {}

    if context_reset:
        clear_state(config.plot_rcparams)
        plot_context.clear()

    close_figs = not context or close_figs

    for i, code_piece in enumerate(code_pieces):

        if not context or config.plot_apply_rcparams:
            clear_state(config.plot_rcparams, close_figs)
        elif close_figs:
            plt.close('all')

        _run_code(
            doctest.script_from_examples(code_piece)
            if is_doctest else code_piece, code_path, ns, function_name)

        images = []
        fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
        for j, figman in enumerate(fig_managers):
            if len(fig_managers) == 1 and len(code_pieces) == 1:
                img = ImageFile(output_base, output_dir)
            elif len(code_pieces) == 1:
                img = ImageFile("%s_%02d" % (output_base, j), output_dir)
            else:
                img = ImageFile("%s_%02d_%02d" % (output_base, i, j),
                                output_dir)
            images.append(img)
            for fmt, dpi in formats:
                try:
                    figman.canvas.figure.savefig(img.filename(fmt), dpi=dpi)
                except Exception as err:
                    raise PlotError(traceback.format_exc()) from err
                img.formats.append(fmt)

        results.append((code_piece, images))

    if not context or config.plot_apply_rcparams:
        clear_state(config.plot_rcparams, close=not context)

    return results
Example #11
0
  name: wendy ; fullname: Wendy Williams

Use columns directly
  >>> for row in conn.execute(s):
  ...     print "name:", row[users.c.name], "; fullname:", row[users.c.fullname]
  name: jack ; fullname: Jack Jones
  name: wendy ; fullname: Wendy Williams
  name: fred ; fullname: Fred Flintstone
  name: mary ; fullname: Mary Contrary

Close the result set
  >>> result.close()

Drop tables
------------

  >>> metadata.drop_all(engine)

"""


from sqlalchemy.dialects import registry
registry.register("monetdb", "sqlalchemy_monetdb.base", "MDBDialect")

import doctest
doctest.testmod()
#print globals()
s = doctest.script_from_examples(globals()["__doc__"])
fout = open("/tmp/debug.py",'w')
fout.write(s)
Example #12
0
#!/usr/bin/python

TXT_FILE = 'izca.txt'
SCRIPT_FILE = 'izca.py'

import sys
import doctest

txt = file(TXT_FILE)
script = doctest.script_from_examples(txt.read())
script_file = file(SCRIPT_FILE, 'w')
script_file.write(script)
script_file.close()

try:
    from epydoc import cli

except ImportError:
    print "================================="
    print "I can't find epydoc, it is required for %s" % sys.argv[0]
    print "You need to install epydoc to use this script"
    print "$ easy_install epydoc"
    print "should do it"
    sys.exit()

sys.argv.append(SCRIPT_FILE)
cli.cli()

print "================================="
print "Point your browser at html/index.html"
print "to see documentation for the code in %s" % TXT_FILE
Example #13
0
def example():
    # Run the example in the Gls class.
    print("--- EXAMPLE CALCULATION ---")
    import doctest
    exec(doctest.script_from_examples(Gls.__doc__))
    print("----------------------------------------------------")
Example #14
0
def convertToPython(doctests, line_filter = None):
    """ Convert give doctest string to static Python code.

    """
    import doctest
    code = doctest.script_from_examples(doctests)

    if code.endswith('\n'):
        code += "#\n"
    else:
        assert False

    output = []
    inside = False

    def getPrintPrefixed(evaluated):
        try:
            node = ast.parse(evaluated.lstrip(), "eval")
        except SyntaxError:
            return evaluated

        if node.body[0].__class__.__name__ == "Expr":
            count = 0

            while evaluated.startswith(' ' * count):
                count += 1

            if sys.version_info < (3,):
                modified = (count-1) * ' ' + "print " + evaluated
                return (count-1) * ' ' + ("print 'Line %d'" % line_number) + "\n" + modified
            else:
                modified = (count-1) * ' ' + "print(" + evaluated + "\n)\n"
                return (count-1) * ' ' + ("print('Line %d'" % line_number) + ")\n" + modified
        else:
            return evaluated

    def getTried(evaluated):
        if sys.version_info < (3,):
            return """
try:
%(evaluated)s
except Exception as __e:
    print "Occurred", type(__e), __e
""" % { "evaluated" : indentedCode(getPrintPrefixed(evaluated).split('\n'), 4) }
        else:
            return """
try:
%(evaluated)s
except Exception as __e:
    print("Occurred", type(__e), __e)
""" % { "evaluated" : indentedCode(getPrintPrefixed(evaluated).split('\n'), 4) }

    def isOpener(evaluated):
        evaluated = evaluated.lstrip()

        if evaluated == "":
            return False

        if evaluated.split()[0] in ("def", "class", "for", "while", "try:", "except", "except:", "finally:", "else:"):
            return True
        else:
            return False

    for line_number, line in enumerate(code.split('\n')):
        # print "->", inside, line

        if line_filter is not None and line_filter(line):
            continue

        if inside and len(line) > 0 and line[0].isalnum() and not isOpener(line):
            output.append(getTried('\n'.join(chunk)))  # @UndefinedVariable

            chunk = []
            inside = False

        if inside and not (line.startswith('#') and line.find("SyntaxError:") != -1):
            chunk.append(line)
        elif line.startswith('#'):
            if line.find("SyntaxError:") != -1:
                # print "Syntax error detected"

                if inside:
                    # print "Dropping chunk", chunk

                    chunk = []
                    inside = False
                else:
                    del output[-1]
        elif isOpener(line):
            inside = True
            chunk = [line]
        elif line.strip() == "":
            output.append(line)
        else:
            output.append(getTried(line))

    return '\n'.join(output).rstrip() + '\n'
Example #15
0
#!/usr/bin/python

TXT_FILE = 'izca.txt'
SCRIPT_FILE = 'izca.py'

import sys
import doctest

txt = file(TXT_FILE)
script = doctest.script_from_examples(txt.read())
script_file = file(SCRIPT_FILE, 'w')
script_file.write(script)
script_file.close()

try:
    from epydoc import cli

except ImportError:
    print "================================="
    print "I can't find epydoc, it is required for %s" % sys.argv[0]
    print "You need to install epydoc to use this script"
    print "$ easy_install epydoc"
    print "should do it"
    sys.exit()  

sys.argv.append(SCRIPT_FILE)
cli.cli()
		 
print "================================="
print "Point your browser at html/index.html"
print "to see documentation for the code in %s" % TXT_FILE
Example #16
0
>>> xx1=xx[xx[:,0]==0,1]
>>> np.var(xx1)
0.66666666666666663
>>> stats._support.collapse(xx[:,:2], (0), (1,), stderr=0, ns=1, cfcn=varfn)
array([[ 0.        ,  0.66666667,  3.        ],
       [ 1.        ,  0.66666667,  3.        ],
       [ 2.        ,  0.66666667,  3.        ]])
>>> stats._support.collapse(xx[:,:], (0), (1,2), stderr=0, ns=1, cfcn=varfn)
array([[ 0.        ,  0.66666667,  3.        ,  0.        ,  3.        ],
       [ 0.        ,  0.66666667,  3.        ,  0.        ,  3.        ],
       [ 1.        ,  0.66666667,  3.        ,  0.        ,  3.        ],
       [ 1.        ,  0.66666667,  3.        ,  0.        ,  3.        ],
       [ 2.        ,  0.66666667,  3.        ,  0.        ,  3.        ],
       [ 2.        ,  0.66666667,  3.        ,  0.        ,  3.        ]])
>>> stats._support.collapse(xx[:,:], (0), (1,2), stderr=0, ns=1, cfcn=None)
array([[ 0.,  1.,  3.,  1.,  3.],
       [ 0.,  1.,  3.,  1.,  3.],
       [ 1.,  1.,  3.,  1.,  3.],
       [ 1.,  1.,  3.,  1.,  3.],
       [ 2.,  1.,  3.,  1.,  3.],
       [ 2.,  1.,  3.,  1.,  3.]])
'''
import doctest
codestr = '\n'.join(
    line for line in doctest.script_from_examples(docstr).split('\n')
    if line[:1] != '#')
#print '\n'.join(codestr)

doctest.testmod(verbose=3)
Example #17
0
# Convert text with examples to a script.
#
# Argument s is a string containing doctest examples.
# The string is converted to a Python script, where doctest examples in s are converted to regular code, and everything else is converted to Python comments.
# The generated script is returned as a string.
#
# For example,
#

import doctest

print(
    doctest.script_from_examples(r"""
    Set x and y to 1 and 2.
    >>> x, y = 1, 2

    Print their sum:
    >>> print(x+y)
    3
"""))

#
# displays:
#

# Set x and y to 1 and 2.

x, y = 1, 2

#
# Print their sum:
Example #18
0
def convertToPython(doctests, line_filter=None):
    """ Convert give doctest string to static Python code.

    """
    # This is convoluted, but it just needs to work, pylint: disable=too-many-branches

    import doctest
    code = doctest.script_from_examples(doctests)

    if code.endswith('\n'):
        code += "#\n"
    else:
        assert False

    output = []
    inside = False

    def getPrintPrefixed(evaluated, line_number):
        try:
            node = ast.parse(evaluated.lstrip(), "eval")
        except SyntaxError:
            return evaluated

        if node.body[0].__class__.__name__ == "Expr":
            count = 0

            while evaluated.startswith(' ' * count):
                count += 1

            if sys.version_info < (3, ):
                modified = (count - 1) * ' ' + "print " + evaluated
                return (count - 1) * ' ' + ("print 'Line %d'" %
                                            line_number) + '\n' + modified
            else:
                modified = (count - 1) * ' ' + "print(" + evaluated + "\n)\n"
                return (count - 1) * ' ' + ("print('Line %d'" %
                                            line_number) + ")\n" + modified
        else:
            return evaluated

    def getTried(evaluated, line_number):
        if sys.version_info < (3, ):
            return """
try:
%(evaluated)s
except Exception as __e:
    print "Occurred", type(__e), __e
""" % {
                "evaluated":
                indentedCode(
                    getPrintPrefixed(evaluated, line_number).split('\n'), 4)
            }
        else:
            return """
try:
%(evaluated)s
except Exception as __e:
    print("Occurred", type(__e), __e)
""" % {
                "evaluated":
                indentedCode(
                    getPrintPrefixed(evaluated, line_number).split('\n'), 4)
            }

    def isOpener(evaluated):
        evaluated = evaluated.lstrip()

        if evaluated == "":
            return False

        return evaluated.split()[0] in ("def", "class", "for", "while", "try:",
                                        "except", "except:", "finally:",
                                        "else:")

    chunk = None
    for line_number, line in enumerate(code.split('\n')):
        # print "->", inside, line

        if line_filter is not None and line_filter(line):
            continue

        if inside and line and line[0].isalnum() and not isOpener(line):
            output.append(getTried('\n'.join(chunk),
                                   line_number))  # @UndefinedVariable

            chunk = []
            inside = False

        if inside and not (line.startswith('#')
                           and line.find("SyntaxError:") != -1):
            chunk.append(line)
        elif line.startswith('#'):
            if line.find("SyntaxError:") != -1:
                # print "Syntax error detected"

                if inside:
                    # print "Dropping chunk", chunk

                    chunk = []
                    inside = False
                else:
                    del output[-1]
        elif isOpener(line):
            inside = True
            chunk = [line]
        elif line.strip() == "":
            output.append(line)
        else:
            output.append(getTried(line, line_number))

    return '\n'.join(output).rstrip() + '\n'
Example #19
0

def create_cookiesman_app(csrfprotect=True, secret='hello!'):
    """app factory"""
    from basics import basics
    from attrsview import attrsview
    from templateview import templateview
    app = Flask(__name__)
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.secret_key = app.config['SECRET_KEY'] = secret
    app.csrf = CSRFProtect(app)
    app.register_blueprint(cookiesman)
    app.register_blueprint(attrsview)
    app.register_blueprint(templateview)
    app.register_blueprint(basics)
    app.add_url_rule("/", endpoint='basics.rulesmap')
    return app


if __name__ == '__main__':

    import sys
    import doctest

    app = create_cookiesman_app()
    if sys.argv[0] != "":
        app.run(debug=True, use_reloader=True)
    else:
        print(doctest.testmod(optionflags=doctest.REPORT_ONLY_FIRST_FAILURE))
        exec(doctest.script_from_examples(__doc__))
Example #20
0
  $ gvjinja.py -m gvjinja gvjinja.env -b |\\
        tee gvjinja-basic.gv | dot -T png > gvjinja-basic.png

:
"""
    pass


if __name__ == '__main__':

    import os
    from importlib import import_module
    import doctest

    if (sys.argv[0] == ""):
        print(doctest.testmod(optionflags=doctest.REPORT_ONLY_FIRST_FAILURE))
        exec(doctest.script_from_examples(gvjinja.__doc__))
    elif (len(sys.argv) == 1 or '-m' != sys.argv[1] or len(sys.argv) < 4):
        print(usage.__doc__, file=sys.stderr)
    else:
        env = import_module(sys.argv[2])
        for attr in sys.argv[3].split("."):
            env = getattr(env, attr)
        if not isinstance(env, Environment):
            raise TypeError(
                '{!r} is not a jinja environment!'.format(env_name))
        if '-b' in sys.argv:
            print(gvjinja.digraphbasic(env))
        else:
            print(gvjinja.digraph(env))
Example #21
0
def example():
    # Run the example in the Gls class.
    print("--- EXAMPLE CALCULATION ---")
    import doctest
    exec(doctest.script_from_examples(Gls.__doc__))
    print("----------------------------------------------------")
Example #22
0

@hello.route('/testcases')
def viewtestcases():
    hrefs = [ (href(url),) for url in gettestcases() ]
    return render_template(
        'tableview.htm',caption='hello',
        tables=[dict(records=hrefs,headings=('testcases',)),])


def create_hello_app():
    """app factory"""
    app = Flask(__name__)
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.register_blueprint(hello)
    app.add_url_rule("/",endpoint='hello.viewtestcases')
    return app


if __name__ == '__main__':

    import sys
    import doctest

    app = create_hello_app()
    if sys.argv[0] != "":
        app.run(debug=True,use_reloader=True)
    else:
        print(doctest.testmod(optionflags=doctest.REPORT_ONLY_FIRST_FAILURE))
        exec(doctest.script_from_examples(gettestcases.__doc__))
def quoted_csv(fname):
    """
    Hello Title
    =================

    Hello Section
    ====================

    Below is some kind of rst list

    x: `int`
        parameter, first
    y: `int`
        parameter, second
    """
    return [line for line in open(fname)]


# quo = quoted_csv(quoted_data_file)

import doctest

if __name__ == "__main__":
    doctest.testmod()
else:
    exec(doctest.script_from_examples(__doc__))
    # This allows to say >>> from here import *
    # and get all vars defined in the doc string placed into the
    # namespace.  A nice separation of production from testing.  But yet
    # the testing stuff is available when you want it.
Example #24
0
    def test_comparison(self):
        comparison_doctest_string = r"""
        >>> V('1.2.0') == '1.2'
        Traceback (most recent call last):
        ...
        TypeError: cannot compare NormalizedVersion and str

        >>> V('1.2') < '1.3'
        Traceback (most recent call last):
        ...
        TypeError: cannot compare NormalizedVersion and str

        >>> V('1.2.0') == V('1.2')
        True
        >>> V('1.2.0') == V('1.2.3')
        False
        >>> V('1.2.0') != V('1.2.3')
        True
        >>> V('1.2.0') < V('1.2.3')
        True
        >>> V('1.2.0') < V('1.2.0')
        False
        >>> V('1.2.0') <= V('1.2.0')
        True
        >>> V('1.2.0') <= V('1.2.3')
        True
        >>> V('1.2.3') <= V('1.2.0')
        False
        >>> V('1.2.0') >= V('1.2.0')
        True
        >>> V('1.2.3') >= V('1.2.0')
        True
        >>> V('1.2.0') >= V('1.2.3')
        False
        >>> V('1.2.0rc1') >= V('1.2.0')
        False
        >>> V('1.0') > V('1.0b2')
        True
        >>> V('1.0') > V('1.0c2')
        True
        >>> V('1.0') > V('1.0rc2')
        True
        >>> V('1.0rc2') > V('1.0rc1')
        True
        >>> V('1.0c4') > V('1.0c1')
        True
        >>> (V('1.0') > V('1.0c2') > V('1.0c1') > V('1.0b2') > V('1.0b1')
        ...  > V('1.0a2') > V('1.0a1'))
        True
        >>> (V('1.0.0') > V('1.0.0c2') > V('1.0.0c1') > V('1.0.0b2') > V('1.0.0b1')
        ...  > V('1.0.0a2') > V('1.0.0a1'))
        True

        >>> V('1.0') < V('1.0.post456.dev623')
        True

        >>> V('1.0.post456.dev623') < V('1.0.post456')  < V('1.0.post1234')
        True

        >>> (V('1.0a1')
        ...  < V('1.0a2.dev456')
        ...  < V('1.0a2')
        ...  < V('1.0a2.1.dev456')  # e.g. need to do a quick post release on 1.0a2
        ...  < V('1.0a2.1')
        ...  < V('1.0b1.dev456')
        ...  < V('1.0b2')
        ...  < V('1.0c1.dev456')
        ...  < V('1.0c1')
        ...  < V('1.0.dev7')
        ...  < V('1.0.dev18')
        ...  < V('1.0.dev456')
        ...  < V('1.0.dev1234')
        ...  < V('1.0rc1')
        ...  < V('1.0rc2')
        ...  < V('1.0')
        ...  < V('1.0.post456.dev623')  # development version of a post release
        ...  < V('1.0.post456'))
        True
        """
        doctest.script_from_examples(comparison_doctest_string)

        # the doctest above is never run, so temporarily add real unit
        # tests until the doctest is rewritten
        self.assertLessEqual(V('1.2.0rc1'), V('1.2.0'))
        self.assertGreater(V('1.0'), V('1.0c2'))
        self.assertGreater(V('1.0'), V('1.0rc2'))
        self.assertGreater(V('1.0rc2'), V('1.0rc1'))
        self.assertGreater(V('1.0c4'), V('1.0c1'))
Example #25
0
                           caption='stack',
                           tables=[
                               getstack(skip=0),
                           ])


def create_basics_app():
    """app factory"""
    from templateview import templateview
    app = Flask(__name__)
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.register_blueprint(templateview)
    app.register_blueprint(basics)
    app.add_url_rule("/", endpoint='basics.rulesmap')
    return app


if __name__ == '__main__':

    import sys
    import doctest

    app = create_basics_app()
    if sys.argv[0] != "":
        app.run(debug=True, use_reloader=True)
    else:
        print(doctest.testmod(optionflags=doctest.REPORT_ONLY_FIRST_FAILURE))
        exec(
            doctest.script_from_examples(
                os.linesep.join([getrules.__doc__, getstack.__doc__])))
Example #26
0
#!/usr/bin/env python
"""
This takes doctest files and turns them into standalone scripts.
"""
import doctest, sys, os

__author__ = "Gavin Huttley"
__copyright__ = "Copyright 2007-2011, The Cogent Project"
__contributors__ = ["Gavin Huttley", "Peter Maxwell"]
__license__ = "BSD"
__version__ = "1.3.0.dev"
__maintainer__ = "Gavin Huttley"
__email__ = "*****@*****.**"
__status__ = "Production"

for filename in sys.argv[1:]:
    print(filename)
    (name, suffix) = os.path.splitext(filename)
    if suffix != ".rst":
        print("not a .rst file")
        continue
    f = open(filename, "r")
    s = "".join(f.readlines())
    f.close()

    s = doctest.script_from_examples(s)
    f = open(name + ".py", "w")
    f.write(s)
    f.close()
    print("->", name + ".py")
Example #27
0
def write_scripts():
    for filename in files:
        with open(os.path.join(doc_root, filename)) as f:
            script = doctest.script_from_examples(f.read())
            with open(filename.replace(".txt", ".py"), 'w') as f_out:
                f_out.write(script)
Example #28
0
#!/usr/bin/env python
"""
This takes doctest files and turns them into standalone scripts.
"""
import doctest, sys, os

__author__ = "Gavin Huttley"
__copyright__ = "Copyright 2007-2011, The Cogent Project"
__contributors__ = ["Gavin Huttley", "Peter Maxwell"]
__license__ = "GPL"
__version__ = "1.3.0.dev"
__maintainer__ = "Gavin Huttley"
__email__ = "*****@*****.**"
__status__ = "Production"

for filename in sys.argv[1:]:
    print filename, 
    (name, suffix) = os.path.splitext(filename)
    if suffix != '.rst':
        print 'not a .rst file'
        continue
    f = open(filename,'r')
    s = ''.join(f.readlines())
    f.close()
    
    s = doctest.script_from_examples(s)
    f = open(name+'.py','w')
    f.write(s)
    f.close()
    print '->', name+'.py'
Example #29
0
 def update_event(self, inp=-1):
     self.set_output_val(0, doctest.script_from_examples(self.input(0)))