def test_execute(statements):
        executor = ThreadExecutor()
        loop = executor.event_loop

        for s, expected_state, expected_results in statements:
            statement = Statement(s, worksheet)
            statement._expected_state = expected_state
            statement._expected_results = expected_results
            statement._got_executing = False
            executor.add_statement(statement)

        def on_statement_executing(executor, statement):
            if hasattr(statement, '_got_state'):
                statement._out_of_order = True
            statement._got_executing = True

        def on_statement_complete(executor, statement):
            statement._got_state = statement.state
            statement._got_results = statement.results
            statement._out_of_order = False

        def on_complete(executor):
            loop.quit()

        def interrupt():
            executor.interrupt()

        global timed_out
        timed_out = False
        def timeout():
            global timed_out
            timed_out = True
            loop.quit()

        executor.sig_statement_executing.connect(on_statement_executing)
        executor.sig_statement_complete.connect(on_statement_complete)
        executor.sig_complete.connect(on_complete)

        if executor.compile():
            executor.execute()

            interrupt_source = threading.Timer(0.5, interrupt)
            interrupt_source.start()

            timeout_source = threading.Timer(1.0, timeout)
            timeout_source.start()
            loop.run()
            if timed_out:
                raise AssertionError("Interrupting ThreadExecutor failed")

            interrupt_source.cancel()
            timeout_source.cancel()

        for s in executor.statements:
            assert_equals(s._got_state, s._expected_state)
            assert_equals(s._got_results, s._expected_results)
            if s._out_of_order:
                raise AssertionError("ThreadExecutor sent 'sig_statement_executing' after 'sig_statement_complete'")
            if s._expected_state == Statement.INTERRUPTED and not s._got_executing:
                raise AssertionError("ThreadExecutor did not send 'sig_statement_executing' within timeout")
    def test_execute(statements):
        executor = ThreadExecutor()

        for s, expected_state, expected_results in statements:
            statement = Statement(s, worksheet)
            statement._expected_state = expected_state
            statement._expected_results = expected_results
            statement._got_executing = False
            executor.add_statement(statement)

        loop = gobject.MainLoop()

        def on_statement_executing(executor, statement):
            if hasattr(statement, '_got_state'):
                statement._out_of_order = True
            statement._got_executing = True

        def on_statement_complete(executor, statement):
            statement._got_state = statement.state
            statement._got_results = statement.results
            statement._out_of_order = False

        def on_complete(executor):
            loop.quit()

        def interrupt():
            executor.interrupt()

        global timed_out
        timed_out = False
        def timeout():
            global timed_out
            timed_out = True
            loop.quit()

        executor.connect('statement-executing', on_statement_executing)
        executor.connect('statement-complete', on_statement_complete)
        executor.connect('complete', on_complete)

        if executor.compile():
            executor.execute()
            interrupt_source = gobject.timeout_add(500, interrupt)
            timeout_source = gobject.timeout_add(1000, timeout)
            loop.run()
            if timed_out:
                raise AssertionError("Interrupting ThreadExecutor failed")
            gobject.source_remove(interrupt_source)
            gobject.source_remove(timeout_source)

        for s in executor.statements:
            assert_equals(s._got_state, s._expected_state)
            assert_equals(s._got_results, s._expected_results)
            if s._out_of_order:
                raise AssertionError("ThreadExecutor sent 'statement-executing' after 'statement-complete'")
            if s._expected_state == Statement.INTERRUPTED and not s._got_executing:
                raise AssertionError("ThreadExecutor did not send 'statement-executing' within timeout")
 def expect_result(text, result):
     s = Statement(text, worksheet)
     s.compile()
     s.execute()
     if s.error_message != None:
         raise Exception(s.error_message)
     if isinstance(result, basestring):
         assert_equals(s.results[0], result)
     else:
         assert_equals(s.results, result)
         pass
     pass
Beispiel #4
0
    def do_test(import_text, evaluate_text, expected):
        nb = Notebook(base)

        scope = {}
        nb.setup_globals(scope)
        
        exec import_text in scope
        result = eval(evaluate_text, scope)

        assert_equals(result, expected)

        cleanup_pyc()
 def expect_result(text, result):
     s = Statement(text, worksheet)
     s.compile()
     s.execute()
     if s.error_message != None :
         raise Exception(s.error_message)
     if isinstance(result, basestring):
         assert_equals(s.results[0], result)
     else:
         assert_equals(s.results, result)
         pass
     pass
    def do_test(import_text, evaluate_text, expected, nb=None):
        if nb is None:
            nb = Notebook(base)

        scope = {}
        nb.setup_globals(scope)

        exec import_text in scope
        result = eval(evaluate_text, scope)

        assert_equals(result, expected)

        cleanup_pyc()
    def test_execute(statements):
        executor = ThreadExecutor()

        for s, expected_state, expected_results in statements:
            statement = Statement(s, worksheet)
            statement._expected_state = expected_state
            statement._expected_results = expected_results
            executor.add_statement(statement)

        loop = gobject.MainLoop()

        def on_statement_complete(executor, statement):
            statement._got_state = statement.state
            statement._got_results = statement.results

        def on_complete(executor):
            loop.quit()

        def interrupt():
            executor.interrupt()

        global timed_out
        timed_out = False
        def timeout():
            global timed_out
            timed_out = True
            loop.quit()

        executor.connect('statement-complete', on_statement_complete)
        executor.connect('complete', on_complete)

        if executor.compile():
            executor.execute()
            interrupt_source = gobject.timeout_add(500, interrupt)
            timeout_source = gobject.timeout_add(1000, timeout)
            loop.run()
            if timed_out:
                raise AssertionError("Interrupting ThreadExecutor failed")
            gobject.source_remove(interrupt_source)
            gobject.source_remove(timeout_source)

        for s in executor.statements:
            assert_equals(s._got_state, s._expected_state)
            assert_equals(s._got_results, s._expected_results)
def test_destroyable_0():
    #--------------------------------------------------------------------------------------
    from test_utils import adjust_environment, assert_equals
    adjust_environment()

    from reinteract.destroyable import Destroyable
    import gobject

    #--------------------------------------------------------------------------------------
    class A(Destroyable, gobject.GObject):
        __gsignals__ = {
            'changed': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ())
        }

    def do_a(*args):
        results.append('a')

    def do_b(*args):
        results.append('b')

    a = A()

    a.connect('changed', do_a)
    handler_id = a.connect('changed', do_b)
    a.disconnect(handler_id)

    results = []
    a.emit('changed')
    assert_equals(results, ['a'])

    a.destroy()

    results = []
    a.emit('changed')
    assert_equals(results, [])

    #--------------------------------------------------------------------------------------
    pass
def test_reunicode_0():
    #--------------------------------------------------------------------------------------
    from test_utils import adjust_environment, assert_equals
    adjust_environment()

    from reinteract.reunicode import decode, escape_unsafe

    #--------------------------------------------------------------------------------------
    def test_escape_unsafe(u, expected):
        assert_equals(escape_unsafe(u), expected)

    # Embedded NUL is \x00
    test_escape_unsafe(u"a\x00b", u"a\\x00b")
    # Test a tab is left untouched
    test_escape_unsafe(u"\t", u"\t")
    # Non-BMP character (represented as surrogates for UCS-2 python)
    test_escape_unsafe(u"\U00010000", u"\\U00010000")
    # Unpaired surrogate
    test_escape_unsafe(u"\ud800", u"\\ud800")

    def test_decode_escaped(s, expected):
        assert_equals(decode(s, escape=True), expected)

    # Valid UTF-8
    test_decode_escaped(u"\u1234".encode("utf8"), u"\u1234")
    # Invalid UTF-8
    test_decode_escaped("abc\x80\x80abc", u"abc\\x80\\x80abc")
    # Mixture
    test_decode_escaped(u"\u1234".encode("utf8") + "\x80", u"\u1234\\x80")
    # embedded NUL
    test_decode_escaped("\x00", "\\x00")

    # Test a non-UTF-8 encoding
    assert_equals(decode("\xc0", encoding="ISO-8859-1"), u"\u00c0")

    #--------------------------------------------------------------------------------------
    pass
def test_reunicode_0():
    #--------------------------------------------------------------------------------------
    from test_utils import adjust_environment, assert_equals
    adjust_environment()

    from reinteract.reunicode import decode, escape_unsafe

    #--------------------------------------------------------------------------------------
    def test_escape_unsafe(u, expected):
        assert_equals(escape_unsafe(u), expected)

    # Embedded NUL is \x00
    test_escape_unsafe(u"a\x00b", u"a\\x00b")
    # Test a tab is left untouched
    test_escape_unsafe(u"\t", u"\t")
    # Non-BMP character (represented as surrogates for UCS-2 python)
    test_escape_unsafe(u"\U00010000", u"\\U00010000")
    # Unpaired surrogate
    test_escape_unsafe(u"\ud800", u"\\ud800")

    def test_decode_escaped(s, expected):
        assert_equals(decode(s, escape=True), expected)

    # Valid UTF-8
    test_decode_escaped(u"\u1234".encode("utf8"), u"\u1234")
    # Invalid UTF-8
    test_decode_escaped("abc\x80\x80abc", u"abc\\x80\\x80abc")
    # Mixture
    test_decode_escaped(u"\u1234".encode("utf8") + "\x80", u"\u1234\\x80")
    # embedded NUL
    test_decode_escaped("\x00", "\\x00")

    # Test a non-UTF-8 encoding
    assert_equals(decode("\xc0", encoding="ISO-8859-1"), u"\u00c0")

    #--------------------------------------------------------------------------------------
    pass
def test_destroyable_0():
    #--------------------------------------------------------------------------------------
    from test_utils import adjust_environment, assert_equals
    adjust_environment()

    from reinteract.destroyable import Destroyable
    import gobject

    #--------------------------------------------------------------------------------------
    class A(Destroyable, gobject.GObject):
        __gsignals__ = {
                'changed': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ())
        }

    def do_a(*args):
        results.append('a')
    def do_b(*args):
        results.append('b')

    a = A()

    a.connect('changed', do_a)
    handler_id = a.connect('changed', do_b)
    a.disconnect(handler_id)

    results = []
    a.emit('changed')
    assert_equals(results, ['a'])

    a.destroy()

    results = []
    a.emit('changed')
    assert_equals(results, [])

    #--------------------------------------------------------------------------------------
    pass
Beispiel #12
0
def test_application_state_0():
    #--------------------------------------------------------------------------------------
    from test_utils import adjust_environment, assert_equals
    adjust_environment()

    from reinteract.application_state import ApplicationState, _section_name
    import tempfile, os

    #--------------------------------------------------------------------------------------
    def test_section_name(path, expected):
        section_name = _section_name(path)
        assert_equals(section_name, expected)

    test_section_name('C:\foo', 'C:\foo')
    test_section_name('foo[]', 'foo%5b%5d')

    #--------------------------------------------------------------------------------------
    f, location = tempfile.mkstemp(".state", "reinteract")
    os.close(f)
    try:
        nb_path = "C:\\Foo\\Bar"

        application_state = ApplicationState(location)
        application_state.notebook_opened(nb_path)
        nb_state = application_state.get_notebook_state(nb_path)
        nb_state.set_open_files([u"foo.rws", u"bar.rws"])
        application_state.flush()

        application_state = ApplicationState(location)

        recent_notebooks = application_state.get_recent_notebooks()
        assert_equals(len(recent_notebooks), 1)
        assert_equals(recent_notebooks[0].path, nb_path)

        nb_state = application_state.get_notebook_state(nb_path)
        assert nb_state.get_last_opened() > 0
        assert_equals(nb_state.get_open_files(), [u"foo.rws", u"bar.rws"])

    finally:
        try:
            os.remove(location)
        except:
            pass
        pass

    #--------------------------------------------------------------------------------------
    pass
Beispiel #13
0
if __name__ == '__main__': #pragma: no cover
    from test_utils import assert_equals

    def test_escape_unsafe(u, expected):
        assert_equals(escape_unsafe(u), expected)

    # Embedded NUL is \x00
    test_escape_unsafe(u"a\x00b", u"a\\x00b")
    # Test a tab is left untouched
    test_escape_unsafe(u"\t", u"\t")
    # Non-BMP character (represented as surrogates for UCS-2 python)
    test_escape_unsafe(u"\U00010000", u"\\U00010000")
    # Unpaired surrogate
    test_escape_unsafe(u"\ud800", u"\\ud800")

    def test_decode_escaped(s, expected):
        assert_equals(decode(s, escape=True), expected)

    # Valid UTF-8
    test_decode_escaped(u"\u1234".encode("utf8"), u"\u1234")
    # Invalid UTF-8
    test_decode_escaped("abc\x80\x80abc", u"abc\\x80\\x80abc")
    # Mixture
    test_decode_escaped(u"\u1234".encode("utf8") + "\x80", u"\u1234\\x80")
    # embedded NUL
    test_decode_escaped("\x00", "\\x00")

    # Test a non-UTF-8 encoding
    assert_equals(decode("\xc0", encoding="ISO-8859-1"), u"\u00c0")
 def test_escape_unsafe(u, expected):
     assert_equals(escape_unsafe(u), expected)
Beispiel #15
0
    # Test import detection
    #

    def get_imports(code):
        rewriter = Rewriter(code)
        rewriter.rewrite_and_compile()
        return rewriter.get_imports()

    def test_imports(code, referenced):
        imports = get_imports(code)
        for module in referenced:
            if not imports.module_is_referenced(module):
                raise AssertionError("'%s': %s should be referenced and isn't",
                                     code, referenced)

    assert_equals(get_imports('a + 1'), None)
    test_imports('import re', ['re'])
    test_imports('import re as r', ['re'])
    test_imports('import re, os as o', ['re', 'os'])

    test_imports('from re import match', ['re'])
    test_imports('from re import match as m', ['re'])
    test_imports('from re import match as m, sub as s', ['re'])
    test_imports('from re import (match as m, sub as s)', ['re'])
    test_imports('from re import *', ['re'])

    assert_equals(get_imports('from __future__ import division').get_future_features(), set(['division']))

    #
    # Test passing in future_features to use in compilation
    #
 def test_quote_list(l, expected):
     quoted = _quote_list(l)
     assert_equals(quoted, expected)
     unquoted = _unquote_list(quoted)
     assert_equals(unquoted, l)
Beispiel #17
0
    def test_execute(statements):
        executor = ThreadExecutor()
        loop = executor.event_loop

        for s, expected_state, expected_results in statements:
            statement = Statement(s, worksheet)
            statement._expected_state = expected_state
            statement._expected_results = expected_results
            statement._got_executing = False
            executor.add_statement(statement)

        def on_statement_executing(executor, statement):
            if hasattr(statement, '_got_state'):
                statement._out_of_order = True
            statement._got_executing = True

        def on_statement_complete(executor, statement):
            statement._got_state = statement.state
            statement._got_results = statement.results
            statement._out_of_order = False

        def on_complete(executor):
            loop.quit()

        def interrupt():
            executor.interrupt()

        global timed_out
        timed_out = False

        def timeout():
            global timed_out
            timed_out = True
            loop.quit()

        executor.sig_statement_executing.connect(on_statement_executing)
        executor.sig_statement_complete.connect(on_statement_complete)
        executor.sig_complete.connect(on_complete)

        if executor.compile():
            executor.execute()

            interrupt_source = threading.Timer(0.5, interrupt)
            interrupt_source.start()

            timeout_source = threading.Timer(1.0, timeout)
            timeout_source.start()
            loop.run()
            if timed_out:
                raise AssertionError("Interrupting ThreadExecutor failed")

            interrupt_source.cancel()
            timeout_source.cancel()

        for s in executor.statements:
            assert_equals(s._got_state, s._expected_state)
            assert_equals(s._got_results, s._expected_results)
            if s._out_of_order:
                raise AssertionError(
                    "ThreadExecutor sent 'sig_statement_executing' after 'sig_statement_complete'"
                )
            if s._expected_state == Statement.INTERRUPTED and not s._got_executing:
                raise AssertionError(
                    "ThreadExecutor did not send 'sig_statement_executing' within timeout"
                )
 def test_quote_list(l, expected):
     quoted = _quote_list(l)
     assert_equals(quoted, expected)
     unquoted = _unquote_list(quoted)
     assert_equals(unquoted, l)
Beispiel #19
0
 def test_section_name(path, expected):
     section_name = _section_name(path)
     assert_equals(section_name, expected)
Beispiel #20
0
def test_rewrite_0():
    #--------------------------------------------------------------------------------------
    from test_utils import adjust_environment, assert_equals
    adjust_environment()

    from reinteract.rewrite import Rewriter, UnsupportedSyntaxError
    import copy, re

    def rewrite_and_compile(code, output_func_name=None, future_features=None, print_func_name=None, encoding="utf8"):
        return Rewriter(code, encoding, future_features).rewrite_and_compile(output_func_name, print_func_name)

    #
    # Test that our intercepting of bare expressions to save the output works
    #
    def test_output(code, expected):
        compiled, _ = rewrite_and_compile(code, output_func_name='reinteract_output')
        
        test_args = []
        def set_test_args(*args): test_args[:] = args

        class Builder:
            def __init__(self, arg=None):
                self.arg = arg

            def __enter__(self):
                return self.arg

            def __exit__(self, exception_type, exception_value, traceback):
                pass

        scope = { 'reinteract_output': set_test_args, '__reinteract_builder': Builder }

        exec compiled in scope

        if tuple(test_args) != tuple(expected):
            raise AssertionError("Got '%s', expected '%s'" % (test_args, expected))

    test_output('a=3', ())
    test_output('1', (1,))
    test_output('1,2', (1,2))
    test_output('1;2', (2,))
    test_output('a=3; a', (3,))
    test_output('def x():\n    1\ny = x()', ())
    test_output('class X():\n    1\n    pass\nx = X()', ())

    #
    # Test our build "keyword"
    #
    test_output('build list() as l:\n    l.append(1)', ([1],))
    test_output('build list():\n    pass', ([],))
    test_output('build as l:\n    l = 42', (42,))
    test_output('build:\n    pass', (None,))

    #
    # Test that our intercepting of print works
    #
    def test_print(code, expected):
        compiled, _ = rewrite_and_compile(code, print_func_name='reinteract_print')
        
        test_args = []
        def set_test_args(*args): test_args[:] = args
        scope = { 'reinteract_print': set_test_args }

        exec compiled in scope

        if tuple(test_args) != tuple(expected):
            raise AssertionError("Got '%s', expected '%s'" % (test_args, expected))

    test_print('a=3', ())
    test_print('print 1', (1,))
    test_print('print 1,2', (1,2))
    test_print('print "",', ("",))
    test_print('for i in [0]: print i', (0,))
    test_print('import sys; print >>sys.stderr, "",', ())

    #
    # Test catching possible mutations of variables
    #
    def test_mutated(code, expected, prepare=None, assert_old=None, assert_new=None):
        compiled, mutated = rewrite_and_compile(code)

        #
        # Basic test - check the root and description for the returned list of mutations
        #
        mutated_root_desc = sorted(((root, description) for (root, description, _) in mutated))

        # Extract the root from a description (just take the first word)
        def expand_root_desc(description):
            m = re.match(r"([a-zA-Z_0-9]+)", description)
            return m.group(1), description

        expected_root_desc = sorted((expand_root_desc(x) for x in expected))

        if tuple(mutated_root_desc) != tuple(expected_root_desc):
            raise AssertionError("Got '%s', expected '%s'" % (mutated, expected))

        # More complex test
        #
        #  a) create old scope, execute 'prepare' in it
        #  b) copy old scope, execute each copy statement
        #  c) execute the code
        #  c) run assertion checks in old and new scope

        if prepare:
            old_scope = { '__copy' : copy.copy }
            exec prepare in old_scope
            new_scope = dict(old_scope)

            for _, _, copy_code in mutated:
                exec copy_code in new_scope

            exec compiled in new_scope

            old_ok = eval(assert_old, old_scope)
            if not old_ok:
                raise AssertionError("Old scope assertion '%s' failed" % assert_old)
            new_ok = eval(assert_new, new_scope)
            if not new_ok:
                raise AssertionError("New scope assertion '%s' failed" % assert_new)

    test_mutated('a[0] = 1', ('a',),
                 'a = [2]', 'a[0] == 2', 'a[0] == 1')
    test_mutated('a[0], b[0] = 1, 2', ('a', 'b'),
                 'a,b = [2],[1]', 'a[0],b[0] == 2,1', 'a[0],b[0] == 1,2')
    test_mutated('a[0], _ = 1', ('a'))
    test_mutated('a[0], b[0] = c[0], d[0] = 1, 2', ('a', 'b', 'c', 'd'))
    test_mutated('a[0][1] = 1', ('a', 'a[...]'),
                 'a = [[0,2],1]', 'a[0][1] == 2', 'a[0][1] == 1')

    # This isn't fully right - in the new scope b should be [1], not []
    test_mutated('a[0].append(1)', ('a', 'a[...]'),
                 'b = []; a = [b]',
                 'b == [] and a == [b]', 'b == [] and a == [[1]]')

    test_mutated('a += 1', ('a',))
    test_mutated('a[0] += 1', ('a', 'a[...]'))

    prepare = """
class A:
    def __init__(self):
        self.b = 1
    def addmul(self, x,y):
        self.b += x * y
    def get_a(self):
        return self.a
    pass
a = A()
a.a = A()
"""

    test_mutated('a.b = 2', ('a',),
                 prepare, 'a.b == 1', 'a.b == 2')
    test_mutated('a.b = 2', ('a',),
                 prepare, 'a.b == 1', 'a.b == 2')
    test_mutated('a.a.b = 2', ('a','a.a'),
                 prepare, 'a.a.b == 1', 'a.a.b == 2')
    test_mutated('a.a.b += 1', ('a','a.a','a.a.b'),
                 prepare, 'a.a.b == 1', 'a.a.b == 2')

    test_mutated('a.addmul(1,2)', ('a',),
                 prepare, 'a.b == 1', 'a.b == 3')
    test_mutated('a.a.addmul(1,2)', ('a', 'a.a'),
                 prepare, 'a.a.b == 1', 'a.a.b == 3')

    # We exempt some methods as being most likely getters.
    test_mutated('a.get_a()', ())
    test_mutated('a.hasA()', ())
    test_mutated('a.isa()', ())

    # These don't actually work properly since we don't know to copy a.a
    # So we just check the descriptions and not the execution
    #
    test_mutated('a.get_a().b = 2', ('a.get_a(...)',))
    test_mutated('a.get_a().a.b = 2', ('a.get_a(...).a',))

    # Tests of skipping mutations when the mutations are actually of
    # local variables
    test_mutated('def f(x):\n    x[1] = 2\n', ())
    test_mutated('def f(y):\n    x = [1]\n    x[1] = 2\n', ())
    test_mutated('def f(x):\n    def g(x):\n        pass', ())
    test_mutated('def f(x):\n    import g', ())
    test_mutated('def f(x):\n    from m import g', ())
    test_mutated('def f(x):\n    from m import g as h\n    h[2] = 3', ())
    test_mutated('class X:\n    x = [1]\n    x[1] = 2\n', ())
    test_mutated('def f(x):\n    class C:\n        pass', ())
    test_mutated('def f((x,)):\n    x[1] = 2\n', ())
    test_mutated('def f(((x,),)):\n    x[1] = 2\n', ())

    # But these are global mutations
    test_mutated('class X:\n    x[1] = 2\n', ('x'))
    test_mutated('class X:\n    global x\n    x[1] = 2\n    x = [1]\n', ('x'))

    # Trying to mutate a global variable inside a function is an error

    def test_unsupported_syntax(code):
        caught_exception = False
        try:
            rewrite_and_compile(code)
        except UnsupportedSyntaxError, e:
            caught_exception = True
        assert_equals(caught_exception, True)
Beispiel #21
0
 def test_escape_unsafe(u, expected):
     assert_equals(escape_unsafe(u), expected)
 def test_quote(s, expected):
     quoted = _quote(s)
     assert_equals(quoted, expected)
     unquoted = _unquote(quoted)
     assert_equals(unquoted, s)
Beispiel #23
0
 def test_decode_escaped(s, expected):
     assert_equals(decode(s, escape=True), expected)
Beispiel #24
0
        write_file("package1/__init__.py", "__all__ = ['mod2']")
        write_file("package1/mod2.py", "b = 2")
        write_file("package2/__init__.py", "")
        write_file("package2/mod3.py", "import package1.mod2\nc = package1.mod2.b + 1")

        do_test("import mod1", "mod1.__file__", os.path.join(base, "mod1.py"))

        do_test("import mod1", "mod1.a", 1)
        do_test("import mod1 as m", "m.a", 1)
        do_test("from mod1 import a", "a", 1)
        do_test("from mod1 import a as a2", "a2", 1)

        do_test("import package1.mod2", "package1.mod2.b", 2)
        do_test("import package1.mod2 as m", "m.b", 2)
        do_test("from package1 import mod2", "mod2.b", 2)
        do_test("from package1 import *", "mod2.b", 2)

        # http://www.reinteract.org/trac/ticket/5
        do_test("import package2.mod3", "package2.mod3.c", 3)

        nb = Notebook(base)
        assert_equals(nb.file_for_absolute_path(os.path.dirname(base)), None)
        assert_equals(nb.file_for_absolute_path(base), None)
        assert_equals(nb.file_for_absolute_path(os.path.join(base, "mod1.py")).path, "mod1.py")
        assert_equals(nb.file_for_absolute_path(os.path.join(base, "package1")), None)
        assert_equals(nb.file_for_absolute_path(os.path.join(base, "package1/")), None)
        assert_equals(nb.file_for_absolute_path(os.path.join(base, "package1/mod2.py")).path, "package1/mod2.py")

    finally:
        cleanup()
def test_statement_0():
    from test_utils import assert_equals, adjust_environment
    adjust_environment()

    from reinteract.statement import Statement

    from reinteract.notebook import Notebook
    nb = Notebook()

    from reinteract.worksheet import Worksheet
    worksheet = Worksheet(nb)

    def expect_result(text, result):
        s = Statement(text, worksheet)
        s.compile()
        s.execute()
        if s.error_message != None :
            raise Exception(s.error_message)
        if isinstance(result, basestring):
            assert_equals(s.results[0], result)
        else:
            assert_equals(s.results, result)
            pass
        pass
    
    # A bare expression should give the repr of the expression
    expect_result("'a'", repr('a'))
    expect_result("1,2", repr((1,2)))

    # Print, on the other hand, gives the string form of the expression, with
    # one result object per output line
    expect_result("print 'a'", 'a')
    expect_result("print 'a', 'b'", ['a b'])
    expect_result("print 'a\\nb'", ['a','b'])

    # Test that we copy a variable before mutating it (when we can detect
    # the mutation)
    s1 = Statement("b = [0]", worksheet)
    s1.compile()
    s1.execute()
    s2 = Statement("b[0] = 1", worksheet, parent=s1)
    s2.compile()
    s2.execute()
    s3 = Statement("b[0]", worksheet, parent=s2)
    s3.compile()
    s3.execute()
    assert_equals(s3.results[0], "1")
    
    s2a = Statement("b[0]", worksheet, parent=s1)
    s2a.compile()
    s2a.execute()
    assert_equals(s2a.results[0], "0")

    # Test __reinteract_wrappers with an unrealistic example
    s1 = Statement("__reinteract_wrappers = [ lambda x: 2 ]", worksheet)
    s1.compile()
    s1.execute()
    s2 = Statement("1", worksheet, parent=s1)
    s2.compile()
    s2.execute()
    assert_equals(s2.results[0], "2")

    # Tests of catching errors
    s1 = Statement("b = ", worksheet)
    assert_equals(s1.compile(), False)
    assert s1.error_message is not None

    s1 = Statement("b", worksheet)
    assert_equals(s1.compile(), True)
    assert_equals(s1.execute(), False)
    assert s1.error_message is not None

    # Tests of 'from __future__ import...'
    s1 = Statement("from __future__ import division", worksheet)
    s1.compile()
    assert_equals(s1.future_features, ['division'])
    s2 = Statement("from __future__ import with_statement", worksheet, parent=s1)
    s2.compile()
    assert_equals(s2.future_features, ['division', 'with_statement'])

    s1 = Statement("import  __future__", worksheet) # just a normal import
    assert_equals(s1.future_features, None)

    # Advanced use of "context manager" protocol
    expect_result('from reinteract.statement import Statement; Statement.get_current() != None', repr(True))

    #--------------------------------------------------------------------------------------
    pass
 def test_decode_escaped(s, expected):
     assert_equals(decode(s, escape=True), expected)
 def test_quote(s, expected):
     quoted = _quote(s)
     assert_equals(quoted, expected)
     unquoted = _unquote(quoted)
     assert_equals(unquoted, s)
        # Test recovering from a runtime error during import
        nb = Notebook(base)
        write_file("mod5.py", "a = b")
        try:
            do_test("import mod5", "mod5.a", 1, nb=nb)
        except NameError, e:
            pass
        # the old and new files will have the same second-resolution timestamps
        cleanup_pyc()
        write_file("mod5.py", "a = 1")
        nb.reset_module_by_filename(os.path.join(base, "mod5.py"))
        do_test("import mod5", "mod5.a", 1, nb=nb)

        nb = Notebook(base)
        assert_equals(nb.file_for_absolute_path(os.path.dirname(base)), None)
        assert_equals(nb.file_for_absolute_path(base), None)
        assert_equals(
            nb.file_for_absolute_path(os.path.join(base, "mod1.py")).path,
            "mod1.py")
        assert_equals(
            nb.file_for_absolute_path(os.path.join(base, "package1")), None)
        assert_equals(
            nb.file_for_absolute_path(os.path.join(base, "package1/")), None)
        assert_equals(
            nb.file_for_absolute_path(os.path.join(base,
                                                   "package1/mod2.py")).path,
            "package1/mod2.py")

        # Simple test of isolation - if this was the same notebook, then
        # we'd need to reset_module_by_filename()
def test_statement_0():
    from test_utils import assert_equals, adjust_environment
    adjust_environment()

    from reinteract.statement import Statement

    from reinteract.notebook import Notebook
    nb = Notebook()

    from reinteract.worksheet import Worksheet
    worksheet = Worksheet(nb)

    def expect_result(text, result):
        s = Statement(text, worksheet)
        s.compile()
        s.execute()
        if s.error_message != None:
            raise Exception(s.error_message)
        if isinstance(result, basestring):
            assert_equals(s.results[0], result)
        else:
            assert_equals(s.results, result)
            pass
        pass

    # A bare expression should give the repr of the expression
    expect_result("'a'", repr('a'))
    expect_result("1,2", repr((1, 2)))

    # Print, on the other hand, gives the string form of the expression, with
    # one result object per output line
    expect_result("print 'a'", 'a')
    expect_result("print 'a', 'b'", ['a b'])
    expect_result("print 'a\\nb'", ['a', 'b'])

    # Test that we copy a variable before mutating it (when we can detect
    # the mutation)
    s1 = Statement("b = [0]", worksheet)
    s1.compile()
    s1.execute()
    s2 = Statement("b[0] = 1", worksheet, parent=s1)
    s2.compile()
    s2.execute()
    s3 = Statement("b[0]", worksheet, parent=s2)
    s3.compile()
    s3.execute()
    assert_equals(s3.results[0], "1")

    s2a = Statement("b[0]", worksheet, parent=s1)
    s2a.compile()
    s2a.execute()
    assert_equals(s2a.results[0], "0")

    # Test __reinteract_wrappers with an unrealistic example
    s1 = Statement("__reinteract_wrappers = [ lambda x: 2 ]", worksheet)
    s1.compile()
    s1.execute()
    s2 = Statement("1", worksheet, parent=s1)
    s2.compile()
    s2.execute()
    assert_equals(s2.results[0], "2")

    # Tests of catching errors
    s1 = Statement("b = ", worksheet)
    assert_equals(s1.compile(), False)
    assert s1.error_message is not None

    s1 = Statement("b", worksheet)
    assert_equals(s1.compile(), True)
    assert_equals(s1.execute(), False)
    assert s1.error_message is not None

    # Tests of 'from __future__ import...'
    s1 = Statement("from __future__ import division", worksheet)
    s1.compile()
    assert_equals(s1.future_features, ['division'])
    s2 = Statement("from __future__ import with_statement",
                   worksheet,
                   parent=s1)
    s2.compile()
    assert_equals(s2.future_features, ['division', 'with_statement'])

    s1 = Statement("import  __future__", worksheet)  # just a normal import
    assert_equals(s1.future_features, None)

    # Advanced use of "context manager" protocol
    expect_result(
        'from reinteract.statement import Statement; Statement.get_current() != None',
        repr(True))

    #--------------------------------------------------------------------------------------
    pass
    test_section_name('foo[]', 'foo%5b%5d')

    ######

    f, location = tempfile.mkstemp(".state", "reinteract")
    os.close(f)
    try:
        nb_path = "C:\\Foo\\Bar"

        application_state = ApplicationState(location)
        application_state.notebook_opened(nb_path)
        nb_state = application_state.get_notebook_state(nb_path)
        nb_state.set_open_files(["foo.rws", "bar.rws"])
        application_state.flush()

        application_state = ApplicationState(location)

        recent_notebooks = application_state.get_recent_notebooks()
        assert_equals(len(recent_notebooks), 1)
        assert_equals(recent_notebooks[0].path, nb_path)

        nb_state = application_state.get_notebook_state(nb_path)
        assert nb_state.get_last_opened() > 0
        assert_equals(nb_state.get_open_files(), ["foo.rws", "bar.rws"])

    finally:
        try:
            os.remove(location)
        except:
            pass