Ejemplo n.º 1
0
    def test_calling_without_ipython(self):
        """Test calling embed_interactive when no IPython is around
        """
        try:
            import builtins
        except ImportError:
            import __builtin__ as builtins

        realimport = builtins.__import__

        def myimport(*args):
            """Monkey patch import"""
            if args[0] in 'IPython':
                raise ImportError
            return realimport(*args)

        my_python = mock.MagicMock()

        if six.PY2:
            builtins_name = '__builtin__.__import__'
        elif six.PY3:
            builtins_name = 'builtins.__import__'
        else:
            raise RuntimeError("Python version not supported")

        with mock.patch(builtins_name, myimport):
            with mock.patch('code.InteractiveConsole', my_python):
                embed_interactive()

        self.assertTrue(my_python.called)
Ejemplo n.º 2
0
def main(default=None,
         commands=None,
         config_spec="",
         tests=None,
         description=None):
    """Parses command line arguments and configuration, then runs the
    appropriate command.
    """
    start_time = datetime.now()
    log.debug("Start: '%s'", " ".join(sys.argv))
    log.debug("Time: '%s'", start_time)

    commands = collect_commands(default, commands or [])

    # Configure the application from the command line and get the
    # command to be run
    run_command, arguments, interactive = configure(
        default, commands, config_spec,
        "Thanks for using %(prog)s." if description is None else description)

    # Store the commands and tests globally
    # I believe global is justified here for simplicity
    if tests is not None:
        global TESTS  # pylint:disable=W0603
        TESTS = tests
    global COMMANDS  # pylint:disable=W0603
    COMMANDS = commands

    # Initialize the main logger based on the configuration
    # and handle the state safely
    with logging_context(), \
        StateHandler(filename=conf['pyexperiment.state_filename'],
                     load=conf['pyexperiment.load_state'],
                     save=conf['pyexperiment.save_state'],
                     rotate_n_files=conf[
                         'pyexperiment.rotate_n_state_files']):

        # Run the command with the supplied arguments
        if run_command is not None:
            result = run_command(*arguments)

            if result is not None:
                print(result)

        # Drop to the interactive console if necessary, passing the result
        if interactive:
            embed_interactive(result=result)

        # After everything is done, print timings if necessary
        if (((isinstance(conf['pyexperiment.print_timings'], bool)
              and conf['pyexperiment.print_timings'])
             or conf['pyexperiment.print_timings'] == 'True')):
            log.print_timings()

        end_time = datetime.now()
        log.debug("End: '%s'", " ".join(sys.argv))
        log.debug("Time: '%s'", end_time)
        log.debug("Took: %.3fs", (end_time - start_time).total_seconds())
Ejemplo n.º 3
0
    def test_calling_old_ipython(self):
        """Test calling embed_interactive calls old ipython if available
        """
        my_python = mock.MagicMock()
        embed = mock.MagicMock()
        my_python.__version__ = '1.2.1'
        my_python.embed = embed
        sys.modules['IPython'] = my_python

        embed_interactive()

        self.assertTrue(embed.called)
        # Old IPython should be called with user_ns not local_ns
        self.assertIn('user_ns', embed.call_args[1])
        self.assertNotIn('local_ns', embed.call_args[1])
Ejemplo n.º 4
0
    def test_calling_ipython(self):
        """Test calling embed_interactive calls ipython 3.0 if available
        """
        my_python = mock.MagicMock()
        embed = mock.MagicMock()
        my_python.__version__ = '3.0.0'
        my_python.embed = embed
        sys.modules['IPython'] = my_python

        embed_interactive()

        self.assertTrue(embed.called)
        # New IPython should not be called with user_ns but local_ns
        self.assertNotIn('user_ns', embed.call_args[1])
        self.assertIn('local_ns', embed.call_args[1])
Ejemplo n.º 5
0
def main(default=None,
         commands=None,
         config_spec="",
         tests=None,
         description=None):
    """Parses command line arguments and configuration, then runs the
    appropriate command.
    """
    start_time = datetime.now()
    log.debug("Start: '%s'", " ".join(sys.argv))
    log.debug("Time: '%s'", start_time)

    commands = collect_commands(default, commands or [])

    # Configure the application from the command line and get the
    # command to be run
    run_command, arguments, interactive = configure(
        default,
        commands,
        config_spec,
        "Thanks for using %(prog)s."
        if description is None else description)

    # Store the commands and tests globally
    # I believe global is justified here for simplicity
    if tests is not None:
        global TESTS   # pylint:disable=W0603
        TESTS = tests
    global COMMANDS   # pylint:disable=W0603
    COMMANDS = commands

    # Initialize the main logger based on the configuration
    # and handle the state safely
    with logging_context(), \
        StateHandler(filename=conf['pyexperiment.state_filename'],
                     load=conf['pyexperiment.load_state'],
                     save=conf['pyexperiment.save_state'],
                     rotate_n_files=conf[
                         'pyexperiment.rotate_n_state_files']):

        # Run the command with the supplied arguments
        if run_command is not None:
            result = run_command(*arguments)

            if result is not None:
                print(result)

        # Drop to the interactive console if necessary, passing the result
        if interactive:
            embed_interactive(result=result)

        # After everything is done, print timings if necessary
        if (((isinstance(conf['pyexperiment.print_timings'], bool)
              and conf['pyexperiment.print_timings'])
             or conf['pyexperiment.print_timings'] == 'True')):
            log.print_timings()

        end_time = datetime.now()
        log.debug("End: '%s'", " ".join(sys.argv))
        log.debug("Time: '%s'", end_time)
        log.debug("Took: %.3fs", (end_time - start_time).total_seconds())