with Debugger():
        remove_html_markup('abc')

if __name__ == "__main__":
    # ignore
    assert not next_inputs()

if __package__ is None or __package__ == "":
    from bookutils import quiz
else:
    from .bookutils import quiz

if __name__ == "__main__":
    quiz("What happens if we enter 'break 2 + 3'?", [
        "A breakpoint is set in Line 2.", "A breakpoint is set in Line 5.",
        "Two breakpoints are set in Lines 2 and 3.",
        "The debugger raises a ValueError exception."
    ], 12345 % 7)

# ## Deleting Breakpoints

if __name__ == "__main__":
    print('\n## Deleting Breakpoints')


class Debugger(Debugger):
    def delete_command(self, arg=""):
        """Delete breakoint in given line. Without given line, clear all breakpoints"""
        if arg:
            try:
                self.breakpoints.remove(int(arg))

if __name__ == "__main__":
    for i, html in enumerate(['<b>foo</b>',
                              '<b>"foo"</b>',
                              '"<b>foo</b>"',
                              '<"b">foo</"b">']):
        result = remove_html_markup(html)
        print("%-2d %-15s %s" % (i + 1, html, result))


if __name__ == "__main__":
    quiz("From the difference between success and failure,"
         " we can already devise some observations about "
         " what's wrong with the output."
         " Which of these can we turn into general hypotheses?",
        ["Double quotes are stripped from the tagged input.",
         "Tags in double quotes are not stripped.",
         "The tag '&lt;b&gt;' is always stripped from the input.",
         "Four-letter words are stripped."], [298 % 33, 1234 % 616])


# ### Testing a Hypothesis

if __name__ == "__main__":
    print('\n### Testing a Hypothesis')




if __name__ == "__main__":
    remove_html_markup('"foo"')
    sys.settrace(None)
    return ret


if __name__ == "__main__":
    remove_html_markup_traced('xyz')

import math

if __name__ == "__main__":
    quiz(
        "What happens if the tracing function returns None"
        " while tracing function f()?"
        " Lookup sys.setttrace() in the Python documentation"
        " or try it out yourself.", [
            'Tracing stops for all functions;'
            ' the tracing function is no longer called',
            'Tracing stops for f(): the tracing function is called when f() returns',
            'Tracing stops for f() the rest of the execution: the tracing function'
            ' is no longer called for calls to f()', 'Nothing changes'
        ], math.log(7.38905609893065))

# ## A Tracer Class

if __name__ == "__main__":
    print('\n## A Tracer Class')


class Tracer(object):
    def __init__(self, file=sys.stdout):
        """Trace a block of code, sending logs to file (default: stdout)"""
示例#4
0
if __name__ == "__main__":
    with DeltaDebugger() as dd:
        mystery(failing_input)

if __name__ == "__main__":
    dd.args()

if __name__ == "__main__":
    dd.min_args()

if __name__ == "__main__":
    quiz(
        "What happens if the function under test does not raise an exception?",
        [
            "Delta debugging searches for the minimal input"
            " that produces the same result",
            "Delta debugging starts a fuzzer to find an exception",
            "Delta debugging raises an exception"
            "Delta debugging runs forever in a loop",
        ], 0**0 + 1**0 + 0**1 + 1**1)

if __name__ == "__main__":
    with ExpectError(NotFailingError):
        with DeltaDebugger() as dd:
            mystery("An input that does not fail")

# ## Usage Examples

if __name__ == "__main__":
    print('\n## Usage Examples')
示例#5
0
    all_notebooks = [
        node for node in change_counter.changes.keys()
        if len(node) == 2 and node[1].endswith('.ipynb')
    ]
    all_notebooks.sort(key=lambda node: change_counter.changes[node],
                       reverse=True)

if __package__ is None or __package__ == "":
    from bookutils import quiz
else:
    from .bookutils import quiz

if __name__ == "__main__":
    quiz("Which two notebooks have seen the most changes over time?", [
        f"`{all_notebooks[3][1].split('.')[0]}`",
        f"`{all_notebooks[1][1].split('.')[0]}`",
        f"`{all_notebooks[2][1].split('.')[0]}`",
        f"`{all_notebooks[0][1].split('.')[0]}`",
    ], [1234 % 3, 3702 / 1234])

if __name__ == "__main__":
    all_notebooks[0][1].split('.')[0], all_notebooks[1][1].split('.')[0]

# ## Past Fixes

if __name__ == "__main__":
    print('\n## Past Fixes')


class FixCounter(ChangeCounter):
    def include(self, m):
        """Include all modifications whose commit messages start with 'Fix:'"""
示例#6
0

if __name__ == "__main__":
    import os
    os.system(f'python -O -c \'assert 2 + 2 == 5; print("Foo")\'')


def fun():
    assert 2 + 2 == 5

if __name__ == "__main__":
    quiz("If we invoke `fun()` and the assertion fails,"
         " which information do we get?",
         [
             "The failing condition (`2 + 2 == 5`)",
             "The location of the assertion in the program",
             "The list of callers",
             "All of the above"
         ],
         123456789 % 5
        )


if __name__ == "__main__":
    with ExpectError():
        fun()


# ## Checking Preconditions

if __name__ == "__main__":
    print('\n## Checking Preconditions')
示例#7
0
if __name__ == "__main__":
    assert patch(version_1, []) == version_1

if __name__ == "__main__":
    print(patch_string(patches[0]))

if __name__ == "__main__":
    print_content(patch(version_1, [patches[0]]))

if __name__ == "__main__":
    print_content(patch(version_1, [patches[1]]))

if __name__ == "__main__":
    quiz("What has changed in version 1 after applying the second patch?", [
        "The initialization of quote is deleted",
        "The condition after `if c == '<'` is expanded",
        "The tag variable gets a different value", "None of the above"
    ], 1 / 1 + 1**1 - 1 % 1 * 1)

# ## Delta Debugging on Patches

if __name__ == "__main__":
    print('\n## Delta Debugging on Patches')


def test_remove_html_markup(patches):
    new_version = patch(version_1, patches)
    exec(new_version, globals())
    assert remove_html_markup('"foo"') == '"foo"'

        print(f"{line_number:4} {marker} {line}", end='')
        line_number += 1


if __name__ == "__main__":
    list_with_coverage(remove_html_markup, c.coverage)

if __package__ is None or __package__ == "":
    from bookutils import quiz
else:
    from .bookutils import quiz

if __name__ == "__main__":
    quiz(
        "Let the input be <code>&quot;&lt;b&gt;Don't do this!&lt;/b&gt;&quot;</code>. "
        "Which of these lines are executed? Use the code to find out!", [
            "<code>tag = True</code>", "<code>tag = False</code>",
            "<code>quote = not quote</code>", "<code>out = out + c</code>"
        ], [ord(c) - ord('a') - 1 for c in 'cdf'])

if __name__ == "__main__":
    with CoverageCollector() as c:
        remove_html_markup("<b>Don't do this!</b>")
    # list_with_coverage(remove_html_markup, c.coverage)

# ## Computing Differences

if __name__ == "__main__":
    print('\n## Computing Differences')

# ### A Base Class for Statistical Debugging
示例#9
0
        print(f"{line_number:4} {marker} {line}", end='')
        line_number += 1


if __name__ == "__main__":
    code_with_coverage(remove_html_markup, c.coverage())

if __package__ is None or __package__ == "":
    from bookutils import quiz
else:
    from .bookutils import quiz

if __name__ == "__main__":
    quiz(
        'Let the input be `"<b>Don\'t do this!</b>"`. '
        "Which of these lines are executed? Use the code to find out!", [
            "`tag = True`", "`tag = False`", "`quote = not quote`",
            "`out = out + c`"
        ], [ord(c) - ord('a') - 1 for c in 'cdf'])

if __name__ == "__main__":
    with CoverageCollector() as c:
        remove_html_markup("<b>Don't do this!</b>")
    # code_with_coverage(remove_html_markup, c.coverage)

# ## Computing Differences

if __name__ == "__main__":
    print('\n## Computing Differences')

# ### A Base Class for Statistical Debugging
示例#10
0
    os.system(f'python -c \'assert 2 + 2 == 5; print("Foo")\'')

if __name__ == "__main__":
    import os
    os.system(f'python -O -c \'assert 2 + 2 == 5; print("Foo")\'')


def fun():
    assert 2 + 2 == 5


if __name__ == "__main__":
    quiz(
        "If we invoke fun() and the assertion fails,"
        " which information do we get?", [
            "The failing condition (2 + 2 == 5)",
            "The location of the assertion in the program",
            "The list of callers", "All of the above"
        ], 123456789 % 5)

if __name__ == "__main__":
    with ExpectError():
        fun()

# ## Checking Preconditions

if __name__ == "__main__":
    print('\n## Checking Preconditions')


def square_root(x):
示例#11
0
    with ExpectError():
        square_root_with_checked_type_annotations(True)

if __name__ == "__main__":
    square_root(True)

if __package__ is None or __package__ == "":
    from bookutils import quiz
else:
    from .bookutils import quiz

if __name__ == "__main__":
    quiz(
        "What happens if we call "
        "`square_root_with_checked_type_annotations(1)`?", [
            "`1` is automatically converted to float. It will pass.",
            "`1` is a subtype of float. It will pass.",
            "`1` is an integer, and no float. The type check will fail.",
            "The function will fail for some other reason."
        ], 1)

if __name__ == "__main__":
    with ExpectError(enforce.exceptions.RuntimeTypeError):
        square_root_with_checked_type_annotations(1)

from typing import Union, Optional


@enforce.runtime_validation
def square_root_with_union_type(x: Union[int, float]) -> float:
    """Computes the square root of x, using the Newton-Raphson method"""
    return square_root(x)