How to use the xdoctest.exceptions function in xdoctest

To help you get started, we’ve selected a few xdoctest examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Erotemic / xdoctest / xdoctest / parser.py View on Github external
print(tb_text)

                print('Failed to parse string = <<<<<<<<<<<')
                print(string)
                print('>>>>>>>>>>>  # end string')

                print('info = {}'.format(ub.repr2(info)))
                print('-----')
                print('orig_ex = {}'.format(orig_ex))
                print('labeled_lines = {}'.format(ub.repr2(labeled_lines)))
                print('grouped_lines = {}'.format(ub.repr2(grouped_lines, nl=3)))
                print('all_parts = {}'.format(ub.repr2(all_parts)))
                print('')

                sys.exit(1)
            raise exceptions.DoctestParseError(
                'Failed to parse doctest in {}'.format(failpoint),
                string=string, info=info, orig_ex=orig_ex)
        if DEBUG > 1:
            print('\n===== FINISHED PARSE ====')
        return all_parts
github Erotemic / xdoctest / xdoctest / parser.py View on Github external
tb_text = ub.indent(tb_text)
                print(tb_text)

                print('Failed to parse string = <{[<{[<{[')
                print(string)
                print(']}>a]}>]}>  # end string')

                print('info = {a}'.format(a=ub.repr2(info)))
                print('-----')
                print('orig_ex = {a}'.format(a=orig_ex))
                print('labeled_lines = {a}'.format(a=ub.repr2(labeled_lines)))
                print('grouped_lines = {a}'.format(a=ub.repr2(grouped_lines, nl=3)))
                print('all_parts = {a}'.format(a=ub.repr2(all_parts)))
                print('')
                # sys.exit(1)
            raise exceptions.DoctestParseError(
                'Failed to parse doctest in {a}'.format(a=failpoint),
                string=string, info=info, orig_ex=orig_ex)
        if DEBUG > 1:
            print('\n===== FINISHED PARSE ====')
        return all_parts
github Erotemic / xdoctest / xdoctest / doctest_example.py View on Github external
got_stdout = cap.text
                            if not runstate['IGNORE_WANT']:
                                part.check(got_stdout, got_eval, runstate,
                                           unmatched=self._unmatched_stdout)
                            # Clear unmatched output when a check passes
                            self._unmatched_stdout = []
                        else:
                            # If a part doesnt have a want allow its output to
                            # be matched by the next part.
                            self._unmatched_stdout.append(cap.text)

                # Handle anything that could go wrong
                except KeyboardInterrupt:  # nocover
                    raise
                except (exceptions.ExitTestException,
                        exceptions._pytest.outcomes.Skipped):
                    if verbose > 0:
                        print('Test gracefully exists')
                    break
                except checker.GotWantException:
                    # When the "got", does't match the "want"
                    self.exc_info = sys.exc_info()
                    if on_error == 'raise':
                        raise
                    break
                except checker.ExtractGotReprException as ex:
                    # When we fail to extract the "got"
                    self.exc_info = sys.exc_info()
                    if on_error == 'raise':
                        raise ex.orig_ex
                    break
                except Exception as _ex_dbg:
github Erotemic / xdoctest / xdoctest / parser.py View on Github external
def balanced_intervals(lines):
                """
                Finds intervals of balanced nesting syntax

                Args:
                    lines (List[str]): lines of source code
                """
                intervals = []
                a = len(lines) - 1
                b = len(lines)
                while b > 0:
                    # move the head pointer up until we become balanced
                    while not static.is_balanced_statement(lines[a:b], only_tokens=True) and a >= 0:
                        a -= 1
                    if a < 0:
                        raise exceptions.IncompleteParseError(
                            'ill-formed doctest: cannot find balanced ps1 lines.')
                    # we found a balanced interval
                    intervals.append((a, b))
                    b = a
                    a = a - 1

                intervals = intervals[::-1]
                return intervals
            intervals = balanced_intervals(lines)
github Erotemic / xdoctest / testing / test_parser.py View on Github external
def test_bad_indent():
    """
    CommandLine:
        python testing/test_parser.py test_bad_indent
    """
    string = utils.codeblock(
        '''
        Example:
            >>> x = [
        # ] bad want indent
        ''')

    self = parser.DoctestParser()
    with pytest.raises(exceptions.DoctestParseError) as exc_info:
        self.parse(string)
    assert exc_info.value.orig_ex.msg.startswith('Bad indentation in doctest')
github Erotemic / xdoctest / xdoctest / core.py View on Github external
fpath=None, eager_parse=True):
    """
    Parses Google-style doctests from a docstr and generates example objects

    Args:
        lineno (int): the line number (starting from 1) of the docstring.
            i.e. if you were to go to this line number in the source file
            the starting quotes of the docstr would be on this line.

    Raises:
        xdoctest.exceptions.MalformedDocstr: if an error occurs in finding google blocks
        xdoctest.exceptions.DoctestParseError: if an error occurs in parsing
    """
    try:
        blocks = docscrape_google.split_google_docblocks(docstr)
    except exceptions.MalformedDocstr:
        print('ERROR PARSING {} GOOGLE BLOCKS IN {} ON line {}'.format(
            callname, modpath, lineno))
        print('Did you forget to make a docstr with newlines raw?')
        raise
    example_blocks = []
    example_tags = ('Example', 'Doctest', 'Script', 'Benchmark')
    for type, block in blocks:
        if type.startswith(example_tags):
            example_blocks.append((type, block))
    for num, (type, (docsrc, offset)) in enumerate(example_blocks):
        # Add one because offset indicates the position of the block-label
        # and the body of the block always starts on the next line.
        label_lineno = lineno + offset
        body_lineno = label_lineno + 1
        example = doctest_example.DocTest(docsrc, modpath, callname, num,
                                          lineno=body_lineno, fpath=fpath,
github Erotemic / xdoctest / xdoctest / core.py View on Github external
msg += 'Original Error: {}\n'.format(repr(ex.orig_ex))

            if isinstance(ex.orig_ex, SyntaxError):
                extra_help = ''
                if ex.orig_ex.text:
                    extra_help += utils.ensure_unicode(ex.orig_ex.text)
                if ex.orig_ex.offset is not None:
                    extra_help += ' ' * (ex.orig_ex.offset - 1) + '^'
                if extra_help:
                    msg += '\n' + extra_help

        # Always warn when something bad is happening.
        # However, dont error if the docstr simply has bad syntax
        print('msg = {}'.format(msg))
        warnings.warn(msg)
        if isinstance(ex, exceptions.MalformedDocstr):
            pass
        elif isinstance(ex, exceptions.DoctestParseError):
            pass
        else:
            raise
    if DEBUG:
        print('Finished parsing {} examples'.format(n_parsed))
github Erotemic / xdoctest / testing / test_parser.py View on Github external
def test_syntax_error():
    string = utils.codeblock('''
        Example:
            >>> 03 = dsrc()
    ''')
    self = parser.DoctestParser()
    with pytest.raises(exceptions.DoctestParseError):
        self.parse(string)
github Erotemic / xdoctest / xdoctest / parser.py View on Github external
# continue current state
            if curr_state in DSRC_DCNT:
                # source parts may consume more than one line
                try:
                    if DEBUG:  # nocover
                        print('completing source')
                    for part, norm_line in _complete_source(line, state_indent, line_iter):
                        if DEBUG > 4:  # nocover
                            print('part = {!r}'.format(part))
                            print('norm_line = {!r}'.format(norm_line))
                            print('curr_state = {!r}'.format(curr_state))
                        if _hasprefix(norm_line, ('...',)):
                            curr_state = DCNT
                        labeled_lines.append((curr_state, part))

                except exceptions.IncompleteParseError:
                    raise
                except SyntaxError:
                    if DEBUG:  # nocover
                        print('<label>')
                        # print('next(line_iter) = {!r}'.format(line_iter))
                        print('state_indent = {!r}'.format(state_indent))
                        print('line = {!r}'.format(line))
                        print('Failed to label source lines')
                        print('Labeled lines so far: &lt;[[[[[[[[[[')
                        for line in labeled_lines:
                            print(line)
                        print(']]]]]]]]]]&gt;')
                        print('</label>')
                    raise
            elif curr_state == WANT:
                labeled_lines.append((curr_state, line))