def test_monospace_fonts_init(self, init_patch, args, config_tmpdir, method, settings, size, family): """Ensure setting fonts.monospace at init works properly. See https://github.com/qutebrowser/qutebrowser/issues/2973 """ if method == 'temp': args.temp_settings = settings elif method == 'auto': autoconfig_file = config_tmpdir / 'autoconfig.yml' lines = (["config_version: 2", "settings:"] + [ " {}:\n global:\n '{}'".format(k, v) for k, v in settings ]) autoconfig_file.write_text('\n'.join(lines), 'utf-8', ensure=True) elif method == 'py': config_py_file = config_tmpdir / 'config.py' lines = ["c.{} = '{}'".format(k, v) for k, v in settings] config_py_file.write_text('\n'.join(lines), 'utf-8', ensure=True) configinit.early_init(args) # Font expected = '{}pt "{}"'.format(size, family) assert config.instance.get('fonts.keyhint') == expected # QtFont font = config.instance.get('fonts.tabs') assert font.pointSize() == size assert font.family() == family
def test_monospace_fonts_init(self, init_patch, args, config_tmpdir, method, settings, size, family): """Ensure setting fonts.monospace at init works properly. See https://github.com/qutebrowser/qutebrowser/issues/2973 """ if method == 'temp': args.temp_settings = settings elif method == 'auto': autoconfig_file = config_tmpdir / 'autoconfig.yml' lines = ["global:"] + [" {}: '{}'".format(k, v) for k, v in settings] autoconfig_file.write_text('\n'.join(lines), 'utf-8', ensure=True) elif method == 'py': config_py_file = config_tmpdir / 'config.py' lines = ["c.{} = '{}'".format(k, v) for k, v in settings] config_py_file.write_text('\n'.join(lines), 'utf-8', ensure=True) configinit.early_init(args) # Font expected = '{}pt "{}"'.format(size, family) assert config.instance.get('fonts.keyhint') == expected # QtFont font = config.instance.get('fonts.tabs') assert font.pointSize() == size assert font.family() == family
def test_late_init(self, init_patch, monkeypatch, fake_save_manager, args, mocker, errors): configinit.early_init(args) if errors: err = configexc.ConfigErrorDesc("Error text", Exception("Exception")) errs = configexc.ConfigFileErrors("config.py", [err]) if errors == 'fatal': errs.fatal = True monkeypatch.setattr(configinit, '_init_errors', errs) msgbox_mock = mocker.patch( 'qutebrowser.config.configinit.msgbox.msgbox', autospec=True) exit_mock = mocker.patch( 'qutebrowser.config.configinit.sys.exit', autospec=True) configinit.late_init(fake_save_manager) fake_save_manager.add_saveable.assert_any_call( 'state-config', unittest.mock.ANY) fake_save_manager.add_saveable.assert_any_call( 'yaml-config', unittest.mock.ANY, unittest.mock.ANY) if errors: assert len(msgbox_mock.call_args_list) == 1 _call_posargs, call_kwargs = msgbox_mock.call_args_list[0] text = call_kwargs['text'].strip() assert text.startswith('Errors occurred while reading config.py:') assert '<b>Error text</b>: Exception' in text assert exit_mock.called == (errors == 'fatal') else: assert not msgbox_mock.called
def test_fonts_defaults_init(self, init_patch, args, config_tmpdir, fake_save_manager, method, settings, size, family): """Ensure setting fonts.default_family at init works properly. See https://github.com/qutebrowser/qutebrowser/issues/2973 and https://github.com/qutebrowser/qutebrowser/issues/5223 """ if method == 'temp': args.temp_settings = settings elif method == 'auto': autoconfig_file = config_tmpdir / 'autoconfig.yml' lines = (["config_version: 2", "settings:"] + [" {}:\n global:\n '{}'".format(k, v) for k, v in settings]) autoconfig_file.write_text('\n'.join(lines), 'utf-8', ensure=True) elif method == 'py': config_py_file = config_tmpdir / 'config.py' lines = ["c.{} = '{}'".format(k, v) for k, v in settings] lines.append("config.load_autoconfig(False)") config_py_file.write_text('\n'.join(lines), 'utf-8', ensure=True) configinit.early_init(args) configinit.late_init(fake_save_manager) # Font expected = '{}pt "{}"'.format(size, family) assert config.instance.get('fonts.keyhint') == expected
def test_setting_monospace_fonts_family(self, init_patch, args): """Make sure setting fonts.monospace after a family works. See https://github.com/qutebrowser/qutebrowser/issues/3130 """ configinit.early_init(args) config.instance.set_str('fonts.web.family.standard', '') config.instance.set_str('fonts.monospace', 'Terminus')
def run(args): """Initialize everything and run the application.""" if args.temp_basedir: args.basedir = tempfile.mkdtemp(prefix='qutebrowser-basedir-') quitter = Quitter(args) objreg.register('quitter', quitter) log.init.debug("Initializing directories...") standarddir.init(args) utils.preload_resources() log.init.debug("Initializing config...") configinit.early_init(args) global qApp qApp = Application(args) qApp.setOrganizationName("qutebrowser") qApp.setApplicationName("qutebrowser") qApp.setDesktopFileName("qutebrowser") qApp.setApplicationVersion(qutebrowser.__version__) qApp.lastWindowClosed.connect(quitter.on_last_window_closed) if args.version: print(version.version()) sys.exit(usertypes.Exit.ok) crash_handler = crashsignal.CrashHandler(app=qApp, quitter=quitter, args=args, parent=qApp) crash_handler.activate() objreg.register('crash-handler', crash_handler) signal_handler = crashsignal.SignalHandler(app=qApp, quitter=quitter, parent=qApp) signal_handler.activate() objreg.register('signal-handler', signal_handler) try: server = ipc.send_or_listen(args) except ipc.Error: # ipc.send_or_listen already displays the error message for us. # We didn't really initialize much so far, so we just quit hard. sys.exit(usertypes.Exit.err_ipc) if server is None: if args.backend is not None: log.init.warning("Backend from the running instance will be used") sys.exit(usertypes.Exit.ok) else: server.got_args.connect(lambda args, target_arg, cwd: process_pos_args( args, cwd=cwd, via_ipc=True, target_arg=target_arg)) init(args, crash_handler) ret = qt_mainloop() return ret
def run(args): """Initialize everything and run the application.""" if args.temp_basedir: args.basedir = tempfile.mkdtemp(prefix='qutebrowser-basedir-') quitter = Quitter(args) objreg.register('quitter', quitter) log.init.debug("Initializing directories...") standarddir.init(args) utils.preload_resources() log.init.debug("Initializing config...") configinit.early_init(args) global q_app q_app = Application(args) q_app.setOrganizationName("qutebrowser") q_app.setApplicationName("qutebrowser") q_app.setDesktopFileName("qutebrowser") q_app.setApplicationVersion(qutebrowser.__version__) q_app.lastWindowClosed.connect(quitter.on_last_window_closed) if args.version: print(version.version()) sys.exit(usertypes.Exit.ok) crash_handler = crashsignal.CrashHandler( app=q_app, quitter=quitter, args=args, parent=q_app) crash_handler.activate() objreg.register('crash-handler', crash_handler) signal_handler = crashsignal.SignalHandler(app=q_app, quitter=quitter, parent=q_app) signal_handler.activate() objreg.register('signal-handler', signal_handler) try: server = ipc.send_or_listen(args) except ipc.Error: # ipc.send_or_listen already displays the error message for us. # We didn't really initialize much so far, so we just quit hard. sys.exit(usertypes.Exit.err_ipc) if server is None: if args.backend is not None: log.init.warning( "Backend from the running instance will be used") sys.exit(usertypes.Exit.ok) else: server.got_args.connect(lambda args, target_arg, cwd: process_pos_args(args, cwd=cwd, via_ipc=True, target_arg=target_arg)) init(args, crash_handler) ret = qt_mainloop() return ret
def test_temp_settings_invalid(self, caplog, init_patch, message_mock, args): """Invalid temp settings should show an error.""" args.temp_settings = [('foo', 'bar')] with caplog.at_level(logging.ERROR): configinit.early_init(args) msg = message_mock.getmsg() assert msg.level == usertypes.MessageLevel.error assert msg.text == "set: NoOptionError - No option 'foo'"
def test_autoconfig_warning_custom(self, init_patch, args, tmp_path, monkeypatch): """Make sure there is no autoconfig warning with --config-py.""" config_py_path = tmp_path / 'config.py' config_py_path.touch() args.config_py = str(config_py_path) monkeypatch.setattr(configinit.standarddir, 'config_py', lambda: str(config_py_path)) configinit.early_init(args)
def test_autoconfig_warning(self, init_patch, args, config_tmpdir, caplog): """Test the warning shown for missing autoconfig loading.""" config_py_file = config_tmpdir / 'config.py' config_py_file.ensure() with caplog.at_level(logging.ERROR): configinit.early_init(args) # Check error messages assert len(configinit._init_errors.errors) == 1 error = configinit._init_errors.errors[0] assert str(error).startswith("autoconfig loading not specified")
def test_monospace_fonts_init(self, init_patch, args): """Ensure setting fonts.monospace at init works properly. See https://github.com/qutebrowser/qutebrowser/issues/2973 """ args.temp_settings = [('fonts.monospace', '"Comic Sans MS"')] configinit.early_init(args) # Font assert config.instance.get('fonts.keyhint') == '8pt "Comic Sans MS"' # QtFont assert config.instance.get('fonts.tabs').family() == 'Comic Sans MS'
def test_force_software_rendering(self, monkeypatch, init_patch, args): """Setting force_software_rendering should set the environment var.""" envvar = 'QT_XCB_FORCE_SOFTWARE_OPENGL' monkeypatch.setattr(configinit.objects, 'backend', usertypes.Backend.QtWebEngine) monkeypatch.delenv(envvar, raising=False) args.temp_settings = [('force_software_rendering', 'true')] args.backend = 'webengine' configinit.early_init(args) assert os.environ[envvar] == '1'
def run(args): """Initialize everything and run the application.""" if args.temp_basedir: args.basedir = tempfile.mkdtemp(prefix='qutebrowser-basedir-') log.init.debug("Main process PID: {}".format(os.getpid())) log.init.debug("Initializing directories...") standarddir.init(args) resources.preload() log.init.debug("Initializing config...") configinit.early_init(args) log.init.debug("Initializing application...") app = Application(args) objects.qapp = app app.setOrganizationName("qutebrowser") app.setApplicationName("qutebrowser") # Default DesktopFileName is org.qutebrowser.qutebrowser, set in `get_argparser()` app.setDesktopFileName(args.desktop_file_name) app.setApplicationVersion(qutebrowser.__version__) if args.version: print(version.version_info()) sys.exit(usertypes.Exit.ok) quitter.init(args) crashsignal.init(q_app=app, args=args, quitter=quitter.instance) try: server = ipc.send_or_listen(args) except ipc.Error: # ipc.send_or_listen already displays the error message for us. # We didn't really initialize much so far, so we just quit hard. sys.exit(usertypes.Exit.err_ipc) if server is None: if args.backend is not None: log.init.warning( "Backend from the running instance will be used") sys.exit(usertypes.Exit.ok) init(args=args) quitter.instance.shutting_down.connect(server.shutdown) server.got_args.connect( lambda args, target_arg, cwd: process_pos_args(args, cwd=cwd, via_ipc=True, target_arg=target_arg)) ret = qt_mainloop() return ret
def test_custom_non_existing_file(self, init_patch, args, tmp_path, caplog, monkeypatch): """Make sure --config-py with a non-existent file doesn't fall back silently.""" config_py_path = tmp_path / 'config.py' assert not config_py_path.exists() args.config_py = str(config_py_path) monkeypatch.setattr(configinit.standarddir, 'config_py', lambda: str(config_py_path)) with caplog.at_level(logging.ERROR): configinit.early_init(args) assert len(configinit._init_errors.errors) == 1 error = configinit._init_errors.errors[0] assert isinstance(error.exception, FileNotFoundError)
def test_monospace_fonts_later(self, init_patch, args): """Ensure setting fonts.monospace after init works properly. See https://github.com/qutebrowser/qutebrowser/issues/2973 """ configinit.early_init(args) changed_options = [] config.instance.changed.connect(changed_options.append) config.instance.set_obj('fonts.monospace', '"Comic Sans MS"') assert 'fonts.keyhint' in changed_options # Font assert config.instance.get('fonts.keyhint') == '10pt "Comic Sans MS"' assert 'fonts.tabs' in changed_options # QtFont assert config.instance.get('fonts.tabs').family() == 'Comic Sans MS' # Font subclass, but doesn't end with "monospace" assert 'fonts.web.family.standard' not in changed_options
def test_monospace_fonts_later(self, init_patch, args): """Ensure setting fonts.monospace after init works properly. See https://github.com/qutebrowser/qutebrowser/issues/2973 """ configinit.early_init(args) changed_options = [] config.instance.changed.connect(changed_options.append) config.instance.set_obj('fonts.monospace', '"Comic Sans MS"') assert 'fonts.keyhint' in changed_options # Font assert config.instance.get('fonts.keyhint') == '8pt "Comic Sans MS"' assert 'fonts.tabs' in changed_options # QtFont assert config.instance.get('fonts.tabs').family() == 'Comic Sans MS' # Font subclass, but doesn't end with "monospace" assert 'fonts.web.family.standard' not in changed_options
def test_config_py(self, init_patch, config_tmpdir, caplog, args, config_py): """Test loading with only a config.py.""" config_py_file = config_tmpdir / 'config.py' if config_py: config_py_lines = [ 'c.colors.hints.bg = "red"', 'config.load_autoconfig(False)' ] if config_py == 'error': config_py_lines.append('c.foo = 42') config_py_file.write_text('\n'.join(config_py_lines), 'utf-8', ensure=True) with caplog.at_level(logging.ERROR): configinit.early_init(args) # Check error messages expected_errors = [] if config_py == 'error': expected_errors.append("While setting 'foo': No option 'foo'") if configinit._init_errors is None: actual_errors = [] else: actual_errors = [ str(err) for err in configinit._init_errors.errors ] assert actual_errors == expected_errors # Make sure things have been init'ed assert isinstance(config.instance, config.Config) assert isinstance(config.key_instance, config.KeyConfig) # Check config values if config_py: expected = 'colors.hints.bg = red' else: expected = '<Default configuration>' assert config.instance.dump_userconfig() == expected
def test_config_py(self, init_patch, config_tmpdir, caplog, args, config_py): """Test loading with only a config.py.""" config_py_file = config_tmpdir / 'config.py' if config_py: config_py_lines = ['c.colors.hints.bg = "red"'] if config_py == 'error': config_py_lines.append('c.foo = 42') config_py_file.write_text('\n'.join(config_py_lines), 'utf-8', ensure=True) with caplog.at_level(logging.ERROR): configinit.early_init(args) # Check error messages expected_errors = [] if config_py == 'error': expected_errors.append("While setting 'foo': No option 'foo'") if configinit._init_errors is None: actual_errors = [] else: actual_errors = [str(err) for err in configinit._init_errors.errors] assert actual_errors == expected_errors # Make sure things have been init'ed objreg.get('config-commands') assert isinstance(config.instance, config.Config) assert isinstance(config.key_instance, config.KeyConfig) # Check config values if config_py: expected = 'colors.hints.bg = red' else: expected = '<Default configuration>' assert config.instance.dump_userconfig() == expected
def test_late_init(init_patch, monkeypatch, fake_save_manager, args, mocker, errors): configinit.early_init(args) if errors: err = configexc.ConfigErrorDesc("Error text", Exception("Exception")) errs = configexc.ConfigFileErrors("config.py", [err]) monkeypatch.setattr(configinit, '_init_errors', errs) msgbox_mock = mocker.patch('qutebrowser.config.configinit.msgbox.msgbox', autospec=True) configinit.late_init(fake_save_manager) fake_save_manager.add_saveable.assert_any_call( 'state-config', unittest.mock.ANY) fake_save_manager.add_saveable.assert_any_call( 'yaml-config', unittest.mock.ANY, unittest.mock.ANY) if errors: assert len(msgbox_mock.call_args_list) == 1 _call_posargs, call_kwargs = msgbox_mock.call_args_list[0] text = call_kwargs['text'].strip() assert text.startswith('Errors occurred while reading config.py:') assert '<b>Error text</b>: Exception' in text else: assert not msgbox_mock.called
def test_autoconfig_yml(self, init_patch, config_tmpdir, caplog, args, load_autoconfig, config_py, invalid_yaml): """Test interaction between config.py and autoconfig.yml.""" # Prepare files autoconfig_file = config_tmpdir / 'autoconfig.yml' config_py_file = config_tmpdir / 'config.py' yaml_lines = { '42': '42', 'list': '[1, 2]', 'unknown': [ 'settings:', ' colors.foobar:', ' global: magenta', 'config_version: 2', ], 'wrong-type': [ 'settings:', ' tabs.position:', ' global: true', 'config_version: 2', ], False: [ 'settings:', ' colors.hints.fg:', ' global: magenta', 'config_version: 2', ], } text = '\n'.join(yaml_lines[invalid_yaml]) autoconfig_file.write_text(text, 'utf-8', ensure=True) if config_py: config_py_lines = ['c.colors.hints.bg = "red"'] if load_autoconfig: config_py_lines.append('config.load_autoconfig()') if config_py == 'error': config_py_lines.append('c.foo = 42') config_py_file.write_text('\n'.join(config_py_lines), 'utf-8', ensure=True) with caplog.at_level(logging.ERROR): configinit.early_init(args) # Check error messages expected_errors = [] if load_autoconfig or not config_py: suffix = ' (autoconfig.yml)' if config_py else '' if invalid_yaml in ['42', 'list']: error = ("While loading data{}: Toplevel object is not a dict" .format(suffix)) expected_errors.append(error) elif invalid_yaml == 'wrong-type': error = ("Error{}: Invalid value 'True' - expected a value of " "type str but got bool.".format(suffix)) expected_errors.append(error) elif invalid_yaml == 'unknown': error = ("While loading options{}: Unknown option " "colors.foobar".format(suffix)) expected_errors.append(error) if config_py == 'error': expected_errors.append("While setting 'foo': No option 'foo'") if configinit._init_errors is None: actual_errors = [] else: actual_errors = [str(err) for err in configinit._init_errors.errors] assert actual_errors == expected_errors # Check config values dump = config.instance.dump_userconfig() if config_py and load_autoconfig and not invalid_yaml: expected = [ 'colors.hints.bg = red', 'colors.hints.fg = magenta', ] elif config_py: expected = ['colors.hints.bg = red'] elif invalid_yaml: expected = ['<Default configuration>'] else: expected = ['colors.hints.fg = magenta'] assert dump == '\n'.join(expected)
def test_autoconfig_yml(self, init_patch, config_tmpdir, caplog, args, load_autoconfig, config_py, invalid_yaml): """Test interaction between config.py and autoconfig.yml.""" # pylint: disable=too-many-locals,too-many-branches # Prepare files autoconfig_file = config_tmpdir / 'autoconfig.yml' config_py_file = config_tmpdir / 'config.py' yaml_text = { '42': '42', 'unknown': 'global:\n colors.foobar: magenta\n', 'wrong-type': 'global:\n tabs.position: true\n', False: 'global:\n colors.hints.fg: magenta\n', } autoconfig_file.write_text(yaml_text[invalid_yaml], 'utf-8', ensure=True) if config_py: config_py_lines = ['c.colors.hints.bg = "red"'] if load_autoconfig: config_py_lines.append('config.load_autoconfig()') if config_py == 'error': config_py_lines.append('c.foo = 42') config_py_file.write_text('\n'.join(config_py_lines), 'utf-8', ensure=True) with caplog.at_level(logging.ERROR): configinit.early_init(args) # Check error messages expected_errors = [] if load_autoconfig or not config_py: suffix = ' (autoconfig.yml)' if config_py else '' if invalid_yaml == '42': error = ("While loading data{}: Toplevel object is not a dict" .format(suffix)) expected_errors.append(error) elif invalid_yaml == 'wrong-type': error = ("Error{}: Invalid value 'True' - expected a value of " "type str but got bool.".format(suffix)) expected_errors.append(error) elif invalid_yaml == 'unknown': error = ("While loading options{}: Unknown option " "colors.foobar".format(suffix)) expected_errors.append(error) if config_py == 'error': expected_errors.append("While setting 'foo': No option 'foo'") if configinit._init_errors is None: actual_errors = [] else: actual_errors = [str(err) for err in configinit._init_errors.errors] assert actual_errors == expected_errors # Check config values if config_py and load_autoconfig and not invalid_yaml: assert config.instance._values == { 'colors.hints.bg': 'red', 'colors.hints.fg': 'magenta', } elif config_py: assert config.instance._values == {'colors.hints.bg': 'red'} elif invalid_yaml: assert config.instance._values == {} else: assert config.instance._values == {'colors.hints.fg': 'magenta'}
def test_temp_settings_valid(self, init_patch, args): args.temp_settings = [('colors.completion.fg', 'magenta')] configinit.early_init(args) assert config.instance.get_obj('colors.completion.fg') == 'magenta'
def test_invalid_change_filter(self, init_patch, args): config.change_filter('foobar') with pytest.raises(configexc.NoOptionError): configinit.early_init(args)
def test_state_init_errors(self, init_patch, args, data_tmpdir, byte): state_file = data_tmpdir / 'state' state_file.write_binary(byte) configinit.early_init(args) assert configinit._init_errors.errors
def test_temp_settings_valid(self, init_patch, args): args.temp_settings = [('colors.completion.fg', 'magenta')] configinit.early_init(args) assert config.instance._values['colors.completion.fg'] == 'magenta'
def test_autoconfig_yml(self, init_patch, config_tmpdir, caplog, args, load_autoconfig, config_py, invalid_yaml): """Test interaction between config.py and autoconfig.yml.""" # Prepare files autoconfig_file = config_tmpdir / 'autoconfig.yml' config_py_file = config_tmpdir / 'config.py' yaml_text = { '42': '42', 'unknown': 'global:\n colors.foobar: magenta\n', 'wrong-type': 'global:\n tabs.position: true\n', False: 'global:\n colors.hints.fg: magenta\n', } autoconfig_file.write_text(yaml_text[invalid_yaml], 'utf-8', ensure=True) if config_py: config_py_lines = ['c.colors.hints.bg = "red"'] if load_autoconfig: config_py_lines.append('config.load_autoconfig()') if config_py == 'error': config_py_lines.append('c.foo = 42') config_py_file.write_text('\n'.join(config_py_lines), 'utf-8', ensure=True) with caplog.at_level(logging.ERROR): configinit.early_init(args) # Check error messages expected_errors = [] if load_autoconfig or not config_py: suffix = ' (autoconfig.yml)' if config_py else '' if invalid_yaml == '42': error = ("While loading data{}: Toplevel object is not a dict" .format(suffix)) expected_errors.append(error) elif invalid_yaml == 'wrong-type': error = ("Error{}: Invalid value 'True' - expected a value of " "type str but got bool.".format(suffix)) expected_errors.append(error) elif invalid_yaml == 'unknown': error = ("While loading options{}: Unknown option " "colors.foobar".format(suffix)) expected_errors.append(error) if config_py == 'error': expected_errors.append("While setting 'foo': No option 'foo'") if configinit._init_errors is None: actual_errors = [] else: actual_errors = [str(err) for err in configinit._init_errors.errors] assert actual_errors == expected_errors # Check config values if config_py and load_autoconfig and not invalid_yaml: assert config.instance._values == { 'colors.hints.bg': 'red', 'colors.hints.fg': 'magenta', } elif config_py: assert config.instance._values == {'colors.hints.bg': 'red'} elif invalid_yaml: assert config.instance._values == {} else: assert config.instance._values == {'colors.hints.fg': 'magenta'}
def run_configinit(self, init_patch, fake_save_manager, args): """Run configinit.early_init() and .late_init().""" configinit.early_init(args) configinit.late_init(fake_save_manager)
def test_autoconfig_yml(self, init_patch, config_tmpdir, # noqa: C901 caplog, args, load_autoconfig, config_py, invalid_yaml): """Test interaction between config.py and autoconfig.yml.""" # Prepare files autoconfig_file = config_tmpdir / 'autoconfig.yml' config_py_file = config_tmpdir / 'config.py' yaml_lines = { '42': '42', 'list': '[1, 2]', 'unknown': [ 'settings:', ' colors.foobar:', ' global: magenta', 'config_version: 2', ], 'wrong-type': [ 'settings:', ' tabs.position:', ' global: true', 'config_version: 2', ], False: [ 'settings:', ' colors.hints.fg:', ' global: magenta', 'config_version: 2', ], } text = '\n'.join(yaml_lines[invalid_yaml]) autoconfig_file.write_text(text, 'utf-8', ensure=True) if config_py: config_py_lines = ['c.colors.hints.bg = "red"'] config_py_lines.append('config.load_autoconfig({})'.format(load_autoconfig)) if config_py == 'error': config_py_lines.append('c.foo = 42') config_py_file.write_text('\n'.join(config_py_lines), 'utf-8', ensure=True) with caplog.at_level(logging.ERROR): configinit.early_init(args) # Check error messages expected_errors = [] if load_autoconfig or not config_py: suffix = ' (autoconfig.yml)' if config_py else '' if invalid_yaml in ['42', 'list']: error = ("While loading data{}: Toplevel object is not a dict" .format(suffix)) expected_errors.append(error) elif invalid_yaml == 'wrong-type': error = ("Error{}: Invalid value 'True' - expected a value of " "type str but got bool.".format(suffix)) expected_errors.append(error) elif invalid_yaml == 'unknown': error = ("While loading options{}: Unknown option " "colors.foobar".format(suffix)) expected_errors.append(error) if config_py == 'error': expected_errors.append("While setting 'foo': No option 'foo'") if configinit._init_errors is None: actual_errors = [] else: actual_errors = [str(err) for err in configinit._init_errors.errors] assert actual_errors == expected_errors # Check config values dump = config.instance.dump_userconfig() if config_py and load_autoconfig and not invalid_yaml: expected = [ 'colors.hints.bg = red', 'colors.hints.fg = magenta', ] elif config_py: expected = ['colors.hints.bg = red'] elif invalid_yaml: expected = ['<Default configuration>'] else: expected = ['colors.hints.fg = magenta'] assert dump == '\n'.join(expected)
def test_config_py_path(self, args, init_patch, config_py_arg): config_py_arg.write('\n'.join(['config.load_autoconfig()', 'c.colors.hints.bg = "red"'])) configinit.early_init(args) expected = 'colors.hints.bg = red' assert config.instance.dump_userconfig() == expected
def test_early_init(init_patch, config_tmpdir, caplog, fake_args, load_autoconfig, config_py, invalid_yaml): # Prepare files autoconfig_file = config_tmpdir / 'autoconfig.yml' config_py_file = config_tmpdir / 'config.py' if invalid_yaml == '42': text = '42' elif invalid_yaml == 'unknown': text = 'global:\n colors.foobar: magenta\n' elif invalid_yaml == 'wrong-type': text = 'global:\n tabs.position: true\n' else: assert not invalid_yaml text = 'global:\n colors.hints.fg: magenta\n' autoconfig_file.write_text(text, 'utf-8', ensure=True) if config_py: config_py_lines = ['c.colors.hints.bg = "red"'] if not load_autoconfig: config_py_lines.append('config.load_autoconfig = False') if config_py == 'error': config_py_lines.append('c.foo = 42') config_py_file.write_text('\n'.join(config_py_lines), 'utf-8', ensure=True) with caplog.at_level(logging.ERROR): configinit.early_init(fake_args) # Check error messages expected_errors = [] if config_py == 'error': expected_errors.append("Errors occurred while reading config.py:\n" " While setting 'foo': No option 'foo'") if load_autoconfig or not config_py: error = "Errors occurred while reading autoconfig.yml:\n" if invalid_yaml == '42': error += " While loading data: Toplevel object is not a dict" expected_errors.append(error) elif invalid_yaml == 'wrong-type': error += (" Error: Invalid value 'True' - expected a value of " "type str but got bool.") expected_errors.append(error) actual_errors = [str(err) for err in configinit._init_errors] assert actual_errors == expected_errors # Make sure things have been init'ed objreg.get('config-commands') assert isinstance(config.instance, config.Config) assert isinstance(config.key_instance, config.KeyConfig) # Check config values if config_py and load_autoconfig and not invalid_yaml: assert config.instance._values == { 'colors.hints.bg': 'red', 'colors.hints.fg': 'magenta', } elif config_py: assert config.instance._values == {'colors.hints.bg': 'red'} elif invalid_yaml: assert config.instance._values == {} else: assert config.instance._values == {'colors.hints.fg': 'magenta'}