Exemple #1
0
 def set_option(self, option, value):
     """
     Set a plugin option in configuration file
     Use a SIGNAL to call it, e.g.:
     plugin.sig_option_changed.emit('show_all', checked)
     """
     CONF.set(self.CONF_SECTION, str(option), value)
Exemple #2
0
    def reset_namespace(self, warning=False, silent=True):
        """Reset the namespace by removing all names defined by the user."""
        reset_str = _("Reset IPython namespace")
        warn_str = _("All user-defined variables will be removed."
                     "<br>Are you sure you want to reset the namespace?")

        if warning:
            box = MessageCheckBox(icon=QMessageBox.Warning, parent=self)
            box.setWindowTitle(reset_str)
            box.set_checkbox_text(_("Don't show again."))
            box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            box.setDefaultButton(QMessageBox.No)

            box.set_checked(False)
            box.set_check_visible(True)
            box.setText(warn_str)

            answer = box.exec_()

            # Update checkbox based on user interaction
            CONF.set('ipython_console', 'show_reset_namespace_warning',
                     not box.is_checked())

            if answer != QMessageBox.Yes:
                return

        if self._reading:
            self.dbg_exec_magic('reset', '-f')
        else:
            if silent:
                self.silent_execute("%reset -f")
                self.refresh_namespacebrowser()
            else:
                self.execute("%reset -f")
Exemple #3
0
 def set_option(self, option, value):
     """
     Set a plugin option in configuration file
     Use a SIGNAL to call it, e.g.:
     plugin.sig_option_changed.emit('show_all', checked)
     """
     CONF.set(self.CONF_SECTION, str(option), value)
Exemple #4
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.main = parent

        # Widgets
        self.pages_widget = QStackedWidget()
        self.pages_widget.setMinimumWidth(600)
        self.contents_widget = QListWidget()
        self.button_reset = QPushButton(_('Reset to defaults'))

        bbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Apply
                                | QDialogButtonBox.Cancel)
        self.apply_btn = bbox.button(QDialogButtonBox.Apply)

        # Widgets setup
        # Destroying the C++ object right after closing the dialog box,
        # otherwise it may be garbage-collected in another QThread
        # (e.g. the editor's analysis thread in Spyder), thus leading to
        # a segmentation fault on UNIX or an application crash on Windows
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowFlags(Qt.Dialog | Qt.WindowStaysOnTopHint)
        self.setWindowTitle(_('Preferences'))
        self.setWindowIcon(ima.icon('configure'))
        self.contents_widget.setMovement(QListView.Static)
        self.contents_widget.setSpacing(1)
        self.contents_widget.setCurrentRow(0)
        self.contents_widget.setMinimumWidth(220)
        self.contents_widget.setMinimumHeight(400)

        # Layout
        hsplitter = QSplitter()
        hsplitter.addWidget(self.contents_widget)
        hsplitter.addWidget(self.pages_widget)
        hsplitter.setStretchFactor(0, 1)
        hsplitter.setStretchFactor(1, 2)

        btnlayout = QHBoxLayout()
        btnlayout.addWidget(self.button_reset)
        btnlayout.addStretch(1)
        btnlayout.addWidget(bbox)

        vlayout = QVBoxLayout()
        vlayout.addWidget(hsplitter)
        vlayout.addLayout(btnlayout)

        self.setLayout(vlayout)

        # Signals and slots
        if self.main:
            self.button_reset.clicked.connect(self.main.reset_spyder)
        self.pages_widget.currentChanged.connect(self.current_page_changed)
        self.contents_widget.currentRowChanged.connect(
            self.pages_widget.setCurrentIndex)
        bbox.accepted.connect(self.accept)
        bbox.rejected.connect(self.reject)
        bbox.clicked.connect(self.button_clicked)

        # Ensures that the config is present on spyder first run
        CONF.set('main', 'interface_language', load_lang_conf())
Exemple #5
0
    def save_connection_settings(self):
        """Save user's kernel connection settings."""

        if not self.save_layout.isChecked():
            return

        is_ssh_key = bool(self.kf_radio.isChecked())
        connection_settings = {
            "json_file_path": self.cf.text(),
            "is_remote": self.rm_group.isChecked(),
            "username": self.un.text(),
            "hostname": self.hn.text(),
            "port": self.pn.text(),
            "is_ssh_keyfile": is_ssh_key,
            "ssh_key_file_path": self.kf.text()
        }
        CONF.set("existing-kernel", "settings", connection_settings)

        try:
            import keyring
            if is_ssh_key:
                keyring.set_password("spyder_remote_kernel",
                                     "ssh_key_passphrase",
                                     self.kfp.text())
            else:
                keyring.set_password("spyder_remote_kernel",
                                     "ssh_password",
                                     self.pw.text())
        except Exception:
            pass
Exemple #6
0
def lsp_manager(qtbot_module, request):
    """LSP manager instance for tests."""
    # Activate pycodestyle and pydocstyle
    CONF.set('lsp-server', 'pycodestyle', True)
    CONF.set('lsp-server', 'pydocstyle', True)

    # Create the manager
    os.environ['SPY_TEST_USE_INTROSPECTION'] = 'True'
    manager = LSPManager(parent=MainWindowMock())

    # Wait for the client to be started
    editor = manager.main.editor
    with qtbot_module.waitSignal(editor.sig_lsp_initialized, timeout=30000):
        manager.start_client('python')

    settings = editor.lsp_editor_settings['python']
    assert all([option in SERVER_CAPABILITES for option in settings.keys()])

    def teardown():
        manager.shutdown()
        os.environ['SPY_TEST_USE_INTROSPECTION'] = 'False'
        CONF.set('lsp-server', 'pycodestyle', False)
        CONF.set('lsp-server', 'pydocstyle', False)

    request.addfinalizer(teardown)
    return manager
Exemple #7
0
def main_window(request):
    """Main Window fixture"""
    # Tests assume inline backend
    CONF.set('ipython_console', 'pylab/backend', 0)

    # Check if we need to use introspection in a given test
    # (it's faster and less memory consuming not to use it!)
    use_introspection = request.node.get_marker('use_introspection')
    if use_introspection:
        os.environ['SPY_TEST_USE_INTROSPECTION'] = 'True'
    else:
        try:
            os.environ.pop('SPY_TEST_USE_INTROSPECTION')
        except KeyError:
            pass

    # Start the window
    app = initialize()
    options, args = get_options()
    window = run_spyder(app, options, args)

    def close_window():
        window.close()

    request.addfinalizer(close_window)
    return window
Exemple #8
0
    def reset_namespace(self, warning=False, silent=True):
        """Reset the namespace by removing all names defined by the user."""
        reset_str = _("Reset IPython namespace")
        warn_str = _("All user-defined variables will be removed."
                     "<br>Are you sure you want to reset the namespace?")

        if warning:
            box = MessageCheckBox(icon=QMessageBox.Warning, parent=self)
            box.setWindowTitle(reset_str)
            box.set_checkbox_text(_("Don't show again."))
            box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            box.setDefaultButton(QMessageBox.No)

            box.set_checked(False)
            box.set_check_visible(True)
            box.setText(warn_str)

            answer = box.exec_()

            # Update checkbox based on user interaction
            CONF.set('ipython_console', 'show_reset_namespace_warning',
                     not box.is_checked())

            if answer != QMessageBox.Yes:
                return

        if self._reading:
            self.dbg_exec_magic('reset', '-f')
        else:
            if silent:
                self.silent_execute("%reset -f")
                self.refresh_namespacebrowser()
            else:
                self.execute("%reset -f")
Exemple #9
0
def lsp_manager(qtbot_module, request):
    """LSP manager instance for tests."""
    # Activate pycodestyle and pydocstyle
    CONF.set('lsp-server', 'pycodestyle', True)
    CONF.set('lsp-server', 'pydocstyle', True)

    # Create the manager
    os.environ['SPY_TEST_USE_INTROSPECTION'] = 'True'
    manager = LSPManager(parent=MainWindowMock())

    # Wait for the client to be started
    editor = manager.main.editor
    with qtbot_module.waitSignal(editor.sig_lsp_initialized, timeout=30000):
        manager.start_client('python')

    settings = editor.lsp_editor_settings['python']
    assert all([option in SERVER_CAPABILITES for option in settings.keys()])

    def teardown():
        manager.shutdown()
        os.environ['SPY_TEST_USE_INTROSPECTION'] = 'False'
        CONF.set('lsp-server', 'pycodestyle', False)
        CONF.set('lsp-server', 'pydocstyle', False)

    request.addfinalizer(teardown)
    return manager
Exemple #10
0
    def save_connection_settings(self):
        """Save user's kernel connection settings."""
        if not self.save_layout.isChecked():
            return

        connection_settings_js = []
        for cs in self.connection_settings_list:
            js = cs.to_json()
            if isinstance(cs, LocalConnectionSettings):
                js['type'] = 'local'
            elif isinstance(cs, RemoteConnectionSettings):
                js['type'] = 'remote'
            connection_settings_js.append(js)

        CONF.set("existing-kernel", "settings", connection_settings_js)

        #
        # try:
        #     import keyring
        #     if is_ssh_key:
        #         keyring.set_password("spyder_remote_kernel",
        #                              "ssh_key_passphrase",
        #                              self.kfp.text())
        #     else:
        #         keyring.set_password("spyder_remote_kernel",
        #                              "ssh_password",
        #                              self.pw.text())
        # except Exception:
        #     pass
        pass
Exemple #11
0
def save_bookmarks(filename, bookmarks):
    """Save all bookmarks from specific file to config."""
    if not osp.isfile(filename):
        return
    slots = load_bookmarks_without_file(filename)
    for slot_num, content in bookmarks.items():
        slots[slot_num] = [filename, content[0], content[1]]
    CONF.set('editor', 'bookmarks', slots)
Exemple #12
0
    def set_option(self, option, value):
        """
        Set a plugin option in configuration file.

        Note: Use sig_option_changed to call it from widgets of the
              same or another plugin.
        """
        CONF.set(self.CONF_SECTION, str(option), value)
Exemple #13
0
    def reset_namespace(self, warning=False, message=False):
        """Reset the namespace by removing all names defined by the user."""
        reset_str = _("Remove all variables")
        warn_str = _("All user-defined variables will be removed. "
                     "Are you sure you want to proceed?")
        kernel_env = self.kernel_manager._kernel_spec.env

        if warning:
            box = MessageCheckBox(icon=QMessageBox.Warning, parent=self)
            box.setWindowTitle(reset_str)
            box.set_checkbox_text(_("Don't show again."))
            box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            box.setDefaultButton(QMessageBox.Yes)

            box.set_checked(False)
            box.set_check_visible(True)
            box.setText(warn_str)

            answer = box.exec_()

            # Update checkbox based on user interaction
            CONF.set('ipython_console', 'show_reset_namespace_warning',
                     not box.is_checked())
            self.ipyclient.reset_warning = not box.is_checked()

            if answer != QMessageBox.Yes:
                return

        try:
            if self._reading:
                self.dbg_exec_magic('reset', '-f')
            else:
                if message:
                    self.reset()
                    self._append_html(_("<br><br>Removing all variables..."
                                        "\n<hr>"),
                                      before_prompt=False)
                self.silent_execute("%reset -f")
                if kernel_env.get('SPY_AUTOLOAD_PYLAB_O') == 'True':
                    self.silent_execute("from pylab import *")
                if kernel_env.get('SPY_SYMPY_O') == 'True':
                    sympy_init = """
                        from __future__ import division
                        from sympy import *
                        x, y, z, t = symbols('x y z t')
                        k, m, n = symbols('k m n', integer=True)
                        f, g, h = symbols('f g h', cls=Function)
                        init_printing()"""
                    self.silent_execute(dedent(sympy_init))
                if kernel_env.get('SPY_RUN_CYTHON') == 'True':
                    self.silent_execute("%reload_ext Cython")
                self.refresh_namespacebrowser()

                if not self.external_kernel:
                    self.silent_execute(
                        'get_ipython().kernel.close_all_mpl_figures()')
        except AttributeError:
            pass
Exemple #14
0
    def get_user_credentials(self):
        """Get user credentials with the login dialog."""
        password = None
        token = None
        (username, remember_me,
         remember_token) = self._get_credentials_from_settings()
        valid_py_os = not (PY2 and sys.platform.startswith('linux'))
        if username and remember_me and valid_py_os:
            # Get password from keyring
            try:
                password = keyring.get_password('github', username)
            except Exception:
                # No safe keyring backend
                if self._show_msgbox:
                    QMessageBox.warning(self.parent_widget,
                                        _('Failed to retrieve password'),
                                        _('It was not possible to retrieve '
                                          'your password. Please introduce '
                                          'it again.'))
        if remember_token and valid_py_os:
            # Get token from keyring
            try:
                token = keyring.get_password('github', 'token')
            except Exception:
                # No safe keyring backend
                if self._show_msgbox:
                    QMessageBox.warning(self.parent_widget,
                                        _('Failed to retrieve token'),
                                        _('It was not possible to retrieve '
                                          'your token. Please introduce it '
                                          'again.'))

        if not running_under_pytest():
            credentials = DlgGitHubLogin.login(self.parent_widget, username,
                                            password, token, remember_me,
                                            remember_token)

            if (credentials['username'] and credentials['password'] and
                    valid_py_os):
                self._store_credentials(credentials['username'],
                                        credentials['password'],
                                        credentials['remember'])
                CONF.set('main', 'report_error/remember_me',
                         credentials['remember'])

            if credentials['token'] and valid_py_os:
                self._store_token(credentials['token'],
                                  credentials['remember_token'])
                CONF.set('main', 'report_error/remember_token',
                         credentials['remember_token'])
        else:
            return dict(username=username,
                        password=password,
                        token='',
                        remember=remember_me,
                        remember_token=remember_token)

        return credentials
Exemple #15
0
def _get_run_configurations():
    history_count = CONF.get('run', 'history', 20)
    try:
        return [(filename, options)
                for filename, options in CONF.get('run', 'configurations', [])
                if osp.isfile(filename)][:history_count]
    except ValueError:
        CONF.set('run', 'configurations', [])
        return []
Exemple #16
0
def ipyconsole(qtbot, request):
    """IPython console fixture."""
    # Tests assume inline backend
    CONF.set('ipython_console', 'pylab/backend', 0)

    # Test the console with a non-ascii temp dir
    non_ascii_dir = request.node.get_marker('non_ascii_dir')
    if non_ascii_dir:
        test_dir = NON_ASCII_DIR
    else:
        test_dir = TEMPDIR

    # Instruct the console to not use a stderr file
    no_stderr_file = request.node.get_marker('no_stderr_file')
    if no_stderr_file:
        test_no_stderr = True
    else:
        test_no_stderr = False

    # Use the automatic backend if requested
    auto_backend = request.node.get_marker('auto_backend')
    if auto_backend:
        CONF.set('ipython_console', 'pylab/backend', 1)

    # Start a Pylab client if requested
    pylab_client = request.node.get_marker('pylab_client')
    is_pylab = True if pylab_client else False

    # Start a Sympy client if requested
    sympy_client = request.node.get_marker('sympy_client')
    is_sympy = True if sympy_client else False

    # Start a Cython client if requested
    cython_client = request.node.get_marker('cython_client')
    is_cython = True if cython_client else False

    # Create the console and a new client
    console = IPythonConsole(parent=None,
                             testing=True,
                             test_dir=test_dir,
                             test_no_stderr=test_no_stderr)
    console.create_new_client(is_pylab=is_pylab,
                              is_sympy=is_sympy,
                              is_cython=is_cython)

    # Close callback
    def close_console():
        console.closing_plugin()
        console.close()

    request.addfinalizer(close_console)

    qtbot.addWidget(console)
    console.show()
    return console
Exemple #17
0
def set_color_scheme(name, color_scheme, replace=True):
    """Set syntax color scheme"""
    section = "color_schemes"
    names = CONF.get("color_schemes", "names", [])
    for key in sh.COLOR_SCHEME_KEYS:
        option = "%s/%s" % (name, key)
        value = CONF.get(section, option, default=None)
        if value is None or replace or name not in names:
            CONF.set(section, option, color_scheme[key])
    names.append(to_text_string(name))
    CONF.set(section, "names", sorted(list(set(names))))
    def create_kernel_spec(self, is_cython=False, **kwargs):
        """Create a kernel spec for our own kernels

        Copied and modified from spyder.plugins.ipythonconsole.IPythonConsole
        """
        ipyconsole = self.main.ipyconsole
        # Before creating our kernel spec, we always need to
        # set this value in spyder.ini
        if spyder.version_info > (3, 3, 1) or not ipyconsole.testing:
            CONF.set('main', 'spyder_pythonpath',
                     ipyconsole.main.get_spyder_pythonpath())
        return MxKernelSpec(is_cython=is_cython)
Exemple #19
0
def conf(request):
    """
    Fixture yielding the Spyder config and resetting it after the test.

    You can use conf.set() to change the Spyder config in your test function.
    If you want to change the config at setup time, then use
    @pytest.mark.parametrize('conf', [(section, label, value)], indirect=True)
    in front of your test function
    """
    if hasattr(request, 'param'):
        CONF.set(*request.param)
    yield CONF
    CONF.reset_to_defaults()
Exemple #20
0
def test_ignore_warnings(qtbot, lsp_codeeditor):
    """Test that the editor is ignoring some warnings."""
    editor, manager = lsp_codeeditor

    # Set text in editor
    editor.set_text(TEXT)

    CONF.set('lsp-server', 'pydocstyle/ignore', 'D100')
    CONF.set('lsp-server', 'pycodestyle/ignore', 'E261')
    manager.update_server_list()
    qtbot.wait(2000)

    # Notify changes
    with qtbot.waitSignal(editor.lsp_response_signal, timeout=30000):
        editor.document_did_change()

    # Get current warnings
    warnings = editor.get_current_warnings()

    expected = [['D103: Missing docstring in public function', 1],
                ['W293 blank line contains whitespace', 2],
                ["undefined name 's'", 5]]

    CONF.set('lsp-server', 'pydocstyle/ignore', '')
    CONF.set('lsp-server', 'pycodestyle/ignore', '')
    manager.update_server_list()
    qtbot.wait(2000)

    assert warnings == expected
Exemple #21
0
def set_font(font, section='main', option='font'):
    """Set font"""
    CONF.set(section, option + '/family', to_text_string(font.family()))
    CONF.set(section, option + '/size', float(font.pointSize()))
    CONF.set(section, option + '/italic', int(font.italic()))
    CONF.set(section, option + '/bold', int(font.bold()))
    FONT_CACHE[(section, option)] = font
Exemple #22
0
def ipyconsole(qtbot, request):
    """IPython console fixture."""
    class MainWindowMock(QWidget):
        def __getattr__(self, attr):
            if attr == 'consoles_menu_actions':
                return []
            else:
                return Mock()

    # Tests assume inline backend
    CONF.set('ipython_console', 'pylab/backend', 0)

    # Test the console with a non-ascii temp dir
    non_ascii_dir = request.node.get_marker('non_ascii_dir')
    if non_ascii_dir:
        test_dir = NON_ASCII_DIR
    else:
        test_dir = None

    # Instruct the console to not use a stderr file
    no_stderr_file = request.node.get_marker('no_stderr_file')
    if no_stderr_file:
        test_no_stderr = True
    else:
        test_no_stderr = False

    # Use the automatic backend if requested
    auto_backend = request.node.get_marker('auto_backend')
    if auto_backend:
        CONF.set('ipython_console', 'pylab/backend', 1)

    # Create the console and a new client
    console = IPythonConsole(parent=MainWindowMock(),
                             testing=True,
                             test_dir=test_dir,
                             test_no_stderr=test_no_stderr)
    console.dockwidget = Mock()
    console.create_new_client()

    # Close callback
    def close_console():
        console.closing_plugin()
        console.close()

    request.addfinalizer(close_console)

    qtbot.addWidget(console)
    console.show()
    return console
Exemple #23
0
def test_editor_docstring_below_def_by_shortcut(qtbot, editor_auto_docstring,
                                                text, expected):
    """Test auto docstring below function definition by shortcut."""
    CONF.set('editor', 'docstring_type', 'Numpydoc')
    editor = editor_auto_docstring
    editor.set_text(text)

    cursor = editor.textCursor()
    cursor.movePosition(QTextCursor.NextBlock)
    cursor.setPosition(QTextCursor.End, QTextCursor.MoveAnchor)
    editor.setTextCursor(cursor)

    editor.writer_docstring.write_docstring_for_shortcut()

    assert editor.toPlainText() == expected
Exemple #24
0
def test_editor_docstring_with_body_googledoc(qtbot, editor_auto_docstring,
                                              text, expected):
    """Test auto docstring of googledoc when the function body is complex."""
    CONF.set('editor', 'docstring_type', 'Googledoc')
    editor = editor_auto_docstring
    editor.set_text(text)

    cursor = editor.textCursor()
    cursor.setPosition(0, QTextCursor.MoveAnchor)
    editor.setTextCursor(cursor)
    writer = editor.writer_docstring

    writer.write_docstring_for_shortcut()

    assert editor.toPlainText() == expected
Exemple #25
0
 def _store_token(self, token, remember=False):
     """Store token for future use."""
     if token and remember:
         try:
             keyring.set_password('github', 'token', token)
         except Exception:
             if self._show_msgbox:
                 QMessageBox.warning(self.parent_widget,
                                     _('Failed to store token'),
                                     _('It was not possible to securely '
                                       'save your token. You will be '
                                       'prompted for your Github token '
                                       'next time you want to report '
                                       'an issue.'))
             remember = False
     CONF.set('main', 'report_error/remember_token', remember)
Exemple #26
0
 def save_historylog(self):
     """Save current history log (all text in console)"""
     title = _("Save history log")
     self.redirect_stdio.emit(False)
     filename, _selfilter = getsavefilename(self, title,
                 self.historylog_filename, "%s (*.log)" % _("History logs"))
     self.redirect_stdio.emit(True)
     if filename:
         filename = osp.normpath(filename)
         try:
             encoding.write(to_text_string(self.get_text_with_eol()),
                            filename)
             self.historylog_filename = filename
             CONF.set('main', 'historylog_filename', filename)
         except EnvironmentError:
             pass
Exemple #27
0
def test_dedicated_consoles(main_window, qtbot):
    """Test running code in dedicated consoles."""
    # ---- Load test file ----
    test_file = osp.join(LOCATION, 'script.py')
    main_window.editor.load(test_file)
    code_editor = main_window.editor.get_focus_widget()

    # --- Set run options for this file ---
    rc = RunConfiguration().get()
    # A dedicated console is used when these two options are False
    rc['current'] = rc['systerm'] = False
    config_entry = (test_file, rc)
    CONF.set('run', 'configurations', [config_entry])

    # --- Run test file and assert that we get a dedicated console ---
    qtbot.keyClick(code_editor, Qt.Key_F5)
    qtbot.wait(500)
    shell = main_window.ipyconsole.get_current_shellwidget()
    control = shell._control
    qtbot.waitUntil(lambda: shell._prompt_html is not None,
                    timeout=SHELL_TIMEOUT)
    nsb = main_window.variableexplorer.get_focus_widget()

    assert len(main_window.ipyconsole.get_clients()) == 2
    assert main_window.ipyconsole.filenames == ['', test_file]
    assert main_window.ipyconsole.tabwidget.tabText(1) == 'script.py/A'
    qtbot.wait(500)
    assert nsb.editor.model.rowCount() == 3

    # --- Assert only runfile text is present and there's no banner text ---
    # See PR #5301
    text = control.toPlainText()
    assert ('runfile' in text) and not ('Python' in text or 'IPython' in text)

    # --- Clean namespace after re-execution ---
    with qtbot.waitSignal(shell.executed):
        shell.execute('zz = -1')
    qtbot.keyClick(code_editor, Qt.Key_F5)
    qtbot.wait(500)
    assert not shell.is_defined('zz')

    # --- Assert runfile text is present after reruns ---
    assert 'runfile' in control.toPlainText()

    # ---- Closing test file and resetting config ----
    main_window.editor.close_file()
    CONF.set('run', 'configurations', [])
Exemple #28
0
    def reset_namespace(self, warning=False, silent=True, message=False):
        """Reset the namespace by removing all names defined by the user."""
        reset_str = _("Remove all variables")
        warn_str = _("All user-defined variables will be removed. "
                     "Are you sure you want to proceed?")

        if warning:
            box = MessageCheckBox(icon=QMessageBox.Warning, parent=self)
            box.setWindowTitle(reset_str)
            box.set_checkbox_text(_("Don't show again."))
            box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            box.setDefaultButton(QMessageBox.Yes)

            box.set_checked(False)
            box.set_check_visible(True)
            box.setText(warn_str)

            answer = box.exec_()

            # Update checkbox based on user interaction
            CONF.set('ipython_console', 'show_reset_namespace_warning',
                     not box.is_checked())
            self.ipyclient.reset_warning = not box.is_checked()

            if answer != QMessageBox.Yes:
                return

        try:
            if self._reading:
                self.dbg_exec_magic('reset', '-f')
            else:
                if silent:
                    if message:
                        self.reset()
                        self._append_html(_("<br><br>Removing all variables..."
                                            "\n<hr>"),
                                          before_prompt=False)
                    self.silent_execute("%reset -f")
                    self.refresh_namespacebrowser()
                else:
                    self.execute("%reset -f")

                if not self.external_kernel:
                    self.silent_execute(
                        'get_ipython().kernel.close_all_mpl_figures()')
        except AttributeError:
            pass
Exemple #29
0
 def _store_credentials(self, username, password, remember=False):
     """Store credentials for future use."""
     if username and password and remember:
         CONF.set('main', 'report_error/username', username)
         try:
             keyring.set_password('github', username, password)
         except Exception:
             if self._show_msgbox:
                 QMessageBox.warning(self.parent_widget,
                                     _('Failed to store password'),
                                     _('It was not possible to securely '
                                       'save your password. You will be '
                                       'prompted for your Github '
                                       'credentials next time you want '
                                       'to report an issue.'))
             remember = False
     CONF.set('main', 'report_error/remember_me', remember)
Exemple #30
0
def test_env_vars():
    """Test that we are correctly encoding env vars in our kernel spec"""
    # Create a variable with the file system encoding and save it
    # in our PYTHONPATH
    env_var = to_fs_from_unicode(u'ñññ')
    CONF.set('main', 'spyder_pythonpath', [env_var])

    # Create a kernel spec
    kernel_spec = SpyderKernelSpec()

    # Assert PYTHONPATH is in env vars and it's not empty
    assert kernel_spec.env['PYTHONPATH'] != ''

    # Assert all env vars are binary strings
    assert all([is_binary_string(v) for v in kernel_spec.env.values()])

    # Remove our entry from PYTHONPATH
    CONF.set('main', 'spyder_pythonpath', [])
    def create_new_client(self, filename=None, give_focus=True):
        """Create a new notebook or load a pre-existing one."""
        # Generate the notebook name (in case of a new one)
        if not filename:
            if not osp.isdir(NOTEBOOK_TMPDIR):
                os.makedirs(NOTEBOOK_TMPDIR)
            nb_name = 'untitled' + str(self.untitled_num) + '.ipynb'
            filename = osp.join(NOTEBOOK_TMPDIR, nb_name)
            nb_contents = nbformat.v4.new_notebook()
            nbformat.write(nb_contents, filename)
            self.untitled_num += 1

        # Save spyder_pythonpath before creating a client
        # because it's needed by our kernel spec.
        if not self.testing:
            CONF.set('main', 'spyder_pythonpath',
                     self.main.get_spyder_pythonpath())

        # Open the notebook with nbopen and get the url we need to render
        try:
            server_info = nbopen(filename)
        except (subprocess.CalledProcessError, NBServerError):
            QMessageBox.critical(
                self, _("Server error"),
                _("The Jupyter Notebook server failed to start or it is "
                  "taking too much time to do it. Please start it in a "
                  "system terminal with the command 'jupyter notebook' to "
                  "check for errors."))
            # Create a welcome widget
            # See issue 93
            self.untitled_num -= 1
            self.create_welcome_client()
            return

        welcome_client = self.create_welcome_client()
        client = NotebookClient(self, filename)
        self.add_tab(client)
        if NOTEBOOK_TMPDIR not in filename:
            self.add_to_recent(filename)
            self.setup_menu_actions()
        client.register(server_info)
        client.load_notebook()
        if welcome_client and not self.testing:
            self.tabwidget.setCurrentIndex(0)
Exemple #32
0
def test_runconfig_workdir(main_window, qtbot, tmpdir):
    """Test runconfig workdir options."""
    CONF.set('run', 'configurations', [])

    # ---- Load test file ----
    test_file = osp.join(LOCATION, 'script.py')
    main_window.editor.load(test_file)
    code_editor = main_window.editor.get_focus_widget()

    # --- Use cwd for this file ---
    rc = RunConfiguration().get()
    rc['file_dir'] = False
    rc['cw_dir'] = True
    config_entry = (test_file, rc)
    CONF.set('run', 'configurations', [config_entry])

    # --- Run test file ---
    shell = main_window.ipyconsole.get_current_shellwidget()
    qtbot.waitUntil(lambda: shell._prompt_html is not None,
                    timeout=SHELL_TIMEOUT)
    qtbot.keyClick(code_editor, Qt.Key_F5)
    qtbot.wait(500)

    # --- Assert we're in cwd after execution ---
    with qtbot.waitSignal(shell.executed):
        shell.execute('import os; current_dir = os.getcwd()')
    assert shell.get_value('current_dir') == get_home_dir()

    # --- Use fixed execution dir for test file ---
    temp_dir = str(tmpdir.mkdir("test_dir"))
    rc['file_dir'] = False
    rc['cw_dir'] = False
    rc['fixed_dir'] = True
    rc['dir'] = temp_dir
    config_entry = (test_file, rc)
    CONF.set('run', 'configurations', [config_entry])

    # --- Run test file ---
    shell = main_window.ipyconsole.get_current_shellwidget()
    qtbot.waitUntil(lambda: shell._prompt_html is not None,
                    timeout=SHELL_TIMEOUT)
    qtbot.keyClick(code_editor, Qt.Key_F5)
    qtbot.wait(500)

    # --- Assert we're in fixed dir after execution ---
    with qtbot.waitSignal(shell.executed):
        shell.execute('import os; current_dir = os.getcwd()')
    assert shell.get_value('current_dir') == temp_dir

    # ---- Closing test file and resetting config ----
    main_window.editor.close_file()
    CONF.set('run', 'configurations', [])
Exemple #33
0
def setup_workingdirectory(qtbot, request):
    """Setup working directory plugin."""
    CONF.reset_to_defaults()
    use_startup_wdir = request.node.get_closest_marker('use_startup_wdir')
    if use_startup_wdir:
        new_wdir = osp.join(os.getcwd(), NEW_DIR)
        if not osp.exists(new_wdir):
            os.mkdir(new_wdir)
        CONF.set('workingdir', 'startup/use_fixed_directory', True)
        CONF.set('workingdir', 'startup/fixed_directory', new_wdir)
    else:
        CONF.set('workingdir', 'startup/use_fixed_directory', False)
        CONF.set('workingdir', 'console/use_fixed_directory', False)
        CONF.set('workingdir', 'startup/fixed_directory', get_home_dir())

    workingdirectory = WorkingDirectory(None)
    qtbot.addWidget(workingdirectory)
    workingdirectory.show()

    return workingdirectory, qtbot
Exemple #34
0
def test_preserve_pypath(tmpdir, default_interpreter):
    """
    Test that we preserve PYTHONPATH in the env vars passed to the kernel
    when an external interpreter is used or not.

    Regression test for issue 8681.
    """
    # Set default interpreter value
    CONF.set('main_interpreter', 'default', default_interpreter)

    # Add a path to PYTHONPATH env var
    pypath = to_text_string(tmpdir.mkdir('test-pypath'))
    os.environ['PYTHONPATH'] = pypath

    # Check that PYTHONPATH is in our kernelspec
    kernel_spec = SpyderKernelSpec()
    assert pypath in kernel_spec.env['PYTHONPATH']

    # Restore default value
    CONF.set('main_interpreter', 'default', True)