Esempio n. 1
0
def test_extension_loading():
    em = get_ipython().extension_manager
    with TemporaryDirectory() as td:
        ext1 = os.path.join(td, 'ext1.py')
        with open(ext1, 'w') as f:
            f.write(ext1_content)

        ext2 = os.path.join(td, 'ext2.py')
        with open(ext2, 'w') as f:
            f.write(ext2_content)

        with prepended_to_syspath(td):
            assert 'ext1' not in em.loaded
            assert 'ext2' not in em.loaded

            # Load extension
            with tt.AssertPrints("Running ext1 load"):
                assert em.load_extension('ext1') is None
            assert 'ext1' in em.loaded

            # Should refuse to load it again
            with tt.AssertNotPrints("Running ext1 load"):
                assert em.load_extension('ext1') == 'already loaded'

            # Reload
            with tt.AssertPrints("Running ext1 unload"):
                with tt.AssertPrints("Running ext1 load", suppress=False):
                    em.reload_extension('ext1')

            # Unload
            with tt.AssertPrints("Running ext1 unload"):
                assert em.unload_extension('ext1') is None

            # Can't unload again
            with tt.AssertNotPrints("Running ext1 unload"):
                assert em.unload_extension('ext1') == 'not loaded'
            assert em.unload_extension('ext2') == 'not loaded'

            # Load extension 2
            with tt.AssertPrints("Running ext2 load"):
                assert em.load_extension('ext2') is None

            # Can't unload this
            assert em.unload_extension('ext2') == 'no unload function'

            # But can reload it
            with tt.AssertPrints("Running ext2 load"):
                em.reload_extension('ext2')
Esempio n. 2
0
def test_time3():
    """Erroneous magic function calls, issue gh-3334"""
    ip = get_ipython()
    ip.user_ns.pop('run', None)

    with tt.AssertNotPrints("not found", channel='stderr'):
        ip.run_cell("%%time\n" "run = 0\n" "run += 1")
Esempio n. 3
0
 def test_changing_py_file(self):
     """Traceback produced if the line where the error occurred is missing?
     
     https://github.com/ipython/ipython/issues/1456
     """
     with TemporaryDirectory() as td:
         fname = os.path.join(td, "foo.py")
         with open(fname, "w") as f:
             f.write(file_1)
         
         with prepended_to_syspath(td):
             ip.run_cell("import foo")
         
         with tt.AssertPrints("ZeroDivisionError"):
             ip.run_cell("foo.f()")
         
         # Make the file shorter, so the line of the error is missing.
         with open(fname, "w") as f:
             f.write(file_2)
         
         # For some reason, this was failing on the *second* call after
         # changing the file, so we call f() twice.
         with tt.AssertNotPrints("Internal Python error", channel='stderr'):
             with tt.AssertPrints("ZeroDivisionError"):
                 ip.run_cell("foo.f()")
             with tt.AssertPrints("ZeroDivisionError"):
                 ip.run_cell("foo.f()")
Esempio n. 4
0
    def test_run_cell(self):
        with tt.AssertPrints('-34'):
            ip.run_cell('print (12 + 22)')

        # A named reference to a number shouldn't be transformed.
        ip.user_ns['n'] = 55
        with tt.AssertNotPrints('-55'):
            ip.run_cell('print (n)')
Esempio n. 5
0
    def test_no_dep(self):
        """
        No deprecation warning should be raised from imported functions
        """
        ip.run_cell("from {} import wrn".format(self.fname))

        with tt.AssertNotPrints("I AM  A WARNING"):
            ip.run_cell("wrn()")
        ip.run_cell("del wrn")
Esempio n. 6
0
    def test_ignore_sys_exit(self):
        """Test the -e option to ignore sys.exit()"""
        src = "import sys; sys.exit(1)"
        self.mktmp(src)
        with tt.AssertPrints('SystemExit'):
            _ip.magic('run %s' % self.fname)

        with tt.AssertNotPrints('SystemExit'):
            _ip.magic('run -e %s' % self.fname)
Esempio n. 7
0
def test_logging_magic_quiet_from_config():
    _ip.config.LoggingMagics.quiet = True
    lm = logging.LoggingMagics(shell=_ip)
    with TemporaryDirectory() as td:
        try:
            with tt.AssertNotPrints(re.compile("Activating.*")):
                lm.logstart(os.path.join(td, "quiet_from_config.log"))
        finally:
            _ip.logger.logstop()
Esempio n. 8
0
    def test_run_debug_twice_with_breakpoint(self):
        """Make a valid python temp file."""
        _ip = get_ipython()
        with tt.fake_input(['b 2', 'c', 'c']):
            _ip.magic('run -d %s' % self.fname)

        with tt.fake_input(['c']):
            with tt.AssertNotPrints('KeyError'):
                _ip.magic('run -d %s' % self.fname)
Esempio n. 9
0
    def test_syntaxerror_no_stacktrace_at_compile_time(self):
        syntax_error_at_compile_time = """
def foo():
    ..
"""
        with tt.AssertPrints("SyntaxError"):
            ip.run_cell(syntax_error_at_compile_time)

        with tt.AssertNotPrints("foo()"):
            ip.run_cell(syntax_error_at_compile_time)
Esempio n. 10
0
    def testLogging(self):
        message = "An unexpected error occurred while tokenizing input"
        cell = 'raise ValueError("""a\nb""")'

        stream = io.StringIO()
        handler = logging.StreamHandler(stream)
        logger = logging.getLogger()
        loglevel = logger.level
        logger.addHandler(handler)
        self.addCleanup(lambda: logger.removeHandler(handler))
        self.addCleanup(lambda: logger.setLevel(loglevel))

        logger.setLevel(logging.INFO)
        with tt.AssertNotPrints(message):
            ip.run_cell(cell)
        self.assertNotIn(message, stream.getvalue())

        logger.setLevel(logging.DEBUG)
        with tt.AssertNotPrints(message):
            ip.run_cell(cell)
        self.assertIn(message, stream.getvalue())
Esempio n. 11
0
    def test_input_rejection(self):
        """Check that NodeTransformers can reject input."""

        expect_exception_tb = tt.AssertPrints("InputRejected: test")
        expect_no_cell_output = tt.AssertNotPrints("'unsafe'", suppress=False)

        # Run the same check twice to verify that the transformer is not
        # disabled after raising.
        with expect_exception_tb, expect_no_cell_output:
            ip.run_cell("'unsafe'")

        with expect_exception_tb, expect_no_cell_output:
            res = ip.run_cell("'unsafe'")

        self.assertIsInstance(res.error_before_exec, InputRejected)
Esempio n. 12
0
 def test_reload_enums(self):
     import enum
     mod_name, mod_fn = self.new_module(
         textwrap.dedent("""
                             from enum import Enum
                             class MyEnum(Enum):
                                 A = 'A'
                                 B = 'B'
                         """))
     self.shell.magic_autoreload("2")
     self.shell.magic_aimport(mod_name)
     self.write_file(
         mod_fn,
         textwrap.dedent("""
                             from enum import Enum
                             class MyEnum(Enum):
                                 A = 'A'
                                 B = 'B'
                                 C = 'C'
                         """))
     with tt.AssertNotPrints(('[autoreload of %s failed:' % mod_name),
                             channel='stderr'):
         self.shell.run_code("pass")  # trigger another reload
Esempio n. 13
0
 def test_suppress_exception_chaining(self):
     with tt.AssertNotPrints("ZeroDivisionError"), \
          tt.AssertPrints("ValueError", suppress=False):
         ip.run_cell(self.SUPPRESS_CHAINING_CODE)
Esempio n. 14
0
    def _check_smoketest(self, use_aimport=True):
        """
        Functional test for the automatic reloader using either
        '%autoreload 1' or '%autoreload 2'
        """

        mod_name, mod_fn = self.new_module("""
x = 9

z = 123  # this item will be deleted

def foo(y):
    return y + 3

class Baz(object):
    def __init__(self, x):
        self.x = x
    def bar(self, y):
        return self.x + y
    @property
    def quux(self):
        return 42
    def zzz(self):
        '''This method will be deleted below'''
        return 99

class Bar:    # old-style class: weakref doesn't work for it on Python < 2.7
    def foo(self):
        return 1
""")

        #
        # Import module, and mark for reloading
        #
        if use_aimport:
            self.shell.magic_autoreload("1")
            self.shell.magic_aimport(mod_name)
            stream = StringIO()
            self.shell.magic_aimport("", stream=stream)
            nt.assert_in(("Modules to reload:\n%s" % mod_name),
                         stream.getvalue())

            with nt.assert_raises(ImportError):
                self.shell.magic_aimport("tmpmod_as318989e89ds")
        else:
            self.shell.magic_autoreload("2")
            self.shell.run_code("import %s" % mod_name)
            stream = StringIO()
            self.shell.magic_aimport("", stream=stream)
            nt.assert_true(
                "Modules to reload:\nall-except-skipped" in stream.getvalue())
        nt.assert_in(mod_name, self.shell.ns)

        mod = sys.modules[mod_name]

        #
        # Test module contents
        #
        old_foo = mod.foo
        old_obj = mod.Baz(9)
        old_obj2 = mod.Bar()

        def check_module_contents():
            nt.assert_equal(mod.x, 9)
            nt.assert_equal(mod.z, 123)

            nt.assert_equal(old_foo(0), 3)
            nt.assert_equal(mod.foo(0), 3)

            obj = mod.Baz(9)
            nt.assert_equal(old_obj.bar(1), 10)
            nt.assert_equal(obj.bar(1), 10)
            nt.assert_equal(obj.quux, 42)
            nt.assert_equal(obj.zzz(), 99)

            obj2 = mod.Bar()
            nt.assert_equal(old_obj2.foo(), 1)
            nt.assert_equal(obj2.foo(), 1)

        check_module_contents()

        #
        # Simulate a failed reload: no reload should occur and exactly
        # one error message should be printed
        #
        self.write_file(mod_fn, """
a syntax error
""")

        with tt.AssertPrints(('[autoreload of %s failed:' % mod_name),
                             channel='stderr'):
            self.shell.run_code("pass")  # trigger reload
        with tt.AssertNotPrints(('[autoreload of %s failed:' % mod_name),
                                channel='stderr'):
            self.shell.run_code("pass")  # trigger another reload
        check_module_contents()

        #
        # Rewrite module (this time reload should succeed)
        #
        self.write_file(
            mod_fn, """
x = 10

def foo(y):
    return y + 4

class Baz(object):
    def __init__(self, x):
        self.x = x
    def bar(self, y):
        return self.x + y + 1
    @property
    def quux(self):
        return 43

class Bar:    # old-style class
    def foo(self):
        return 2
""")

        def check_module_contents():
            nt.assert_equal(mod.x, 10)
            nt.assert_false(hasattr(mod, 'z'))

            nt.assert_equal(old_foo(0), 4)  # superreload magic!
            nt.assert_equal(mod.foo(0), 4)

            obj = mod.Baz(9)
            nt.assert_equal(old_obj.bar(1), 11)  # superreload magic!
            nt.assert_equal(obj.bar(1), 11)

            nt.assert_equal(old_obj.quux, 43)
            nt.assert_equal(obj.quux, 43)

            nt.assert_false(hasattr(old_obj, 'zzz'))
            nt.assert_false(hasattr(obj, 'zzz'))

            obj2 = mod.Bar()
            nt.assert_equal(old_obj2.foo(), 2)
            nt.assert_equal(obj2.foo(), 2)

        self.shell.run_code("pass")  # trigger reload
        check_module_contents()

        #
        # Another failure case: deleted file (shouldn't reload)
        #
        os.unlink(mod_fn)

        self.shell.run_code("pass")  # trigger reload
        check_module_contents()

        #
        # Disable autoreload and rewrite module: no reload should occur
        #
        if use_aimport:
            self.shell.magic_aimport("-" + mod_name)
            stream = StringIO()
            self.shell.magic_aimport("", stream=stream)
            nt.assert_true(("Modules to skip:\n%s" %
                            mod_name) in stream.getvalue())

            # This should succeed, although no such module exists
            self.shell.magic_aimport("-tmpmod_as318989e89ds")
        else:
            self.shell.magic_autoreload("0")

        self.write_file(mod_fn, """
x = -99
""")

        self.shell.run_code("pass")  # trigger reload
        self.shell.run_code("pass")
        check_module_contents()

        #
        # Re-enable autoreload: reload should now occur
        #
        if use_aimport:
            self.shell.magic_aimport(mod_name)
        else:
            self.shell.magic_autoreload("")

        self.shell.run_code("pass")  # trigger reload
        nt.assert_equal(mod.x, -99)
Esempio n. 15
0
def test_timeit_quiet():
    """
    test quiet option of timeit magic
    """
    with tt.AssertNotPrints("loops"):
        _ip.run_cell("%timeit -n1 -r1 -q 1")
Esempio n. 16
0
def test_timeit_return_quiet():
    with tt.AssertNotPrints("loops"):
        res = _ip.run_line_magic('timeit', '-n1 -r1 -q -o 1')
    assert (res is not None)
Esempio n. 17
0
 def test_no_recursion(self):
     with tt.AssertNotPrints("frames repeated"):
         ip.run_cell("non_recurs()")
Esempio n. 18
0
 def test_syntaxerror_without_lineno(self):
     with tt.AssertNotPrints("TypeError"):
         with tt.AssertPrints("line unknown"):
             ip.run_cell("raise SyntaxError()")