Start fixing test_configfiles.py

This commit is contained in:
Florian Bruhin 2018-02-19 20:26:38 +01:00
parent 19148a4593
commit 5d63dfb24c

View File

@ -38,6 +38,36 @@ def configdata_init():
configdata.init() configdata.init()
class AutoConfigHelper:
"""A helper to easily create/validate autoconfig.yml files."""
def __init__(self, config_tmpdir):
self.fobj = config_tmpdir / 'autoconfig.yml'
def write(self, values):
data = {'config_version': 1, 'settings': values}
with self.fobj.open('w', encoding='utf-8') as f:
utils.yaml_dump(data, f)
def write_raw(self, text):
self.fobj.write_text(text, encoding='utf-8', ensure=True)
def read(self):
with self.fobj.open('r', encoding='utf-8') as f:
data = utils.yaml_load(f)
assert data['config_version'] == 1
return data['settings']
def read_raw(self):
return self.fobj.read_text('utf-8')
@pytest.fixture
def autoconfig(config_tmpdir):
return AutoConfigHelper(config_tmpdir)
@pytest.mark.parametrize('old_data, insert, new_data', [ @pytest.mark.parametrize('old_data, insert, new_data', [
(None, False, '[general]\n\n[geometry]\n\n'), (None, False, '[general]\n\n[geometry]\n\n'),
('[general]\nfooled = true', False, '[general]\n\n[geometry]\n\n'), ('[general]\nfooled = true', False, '[general]\n\n[geometry]\n\n'),
@ -75,49 +105,44 @@ class TestYaml:
@pytest.mark.parametrize('old_config', [ @pytest.mark.parametrize('old_config', [
None, None,
'global:\n colors.hints.fg: magenta', {'colors.hints.fg': {'global': 'magenta'}}
]) ])
@pytest.mark.parametrize('insert', [True, False]) @pytest.mark.parametrize('insert', [True, False])
def test_yaml_config(self, yaml, config_tmpdir, old_config, insert): def test_yaml_config(self, yaml, autoconfig, old_config, insert):
autoconfig = config_tmpdir / 'autoconfig.yml'
if old_config is not None: if old_config is not None:
autoconfig.write_text(old_config, 'utf-8') autoconfig.write(old_config)
yaml.load() yaml.load()
if insert: if insert:
yaml['tabs.show'] = 'never' yaml.set_obj('tabs.show', 'never')
yaml._save() yaml._save()
if not insert and old_config is None: if not insert and old_config is None:
lines = [] lines = []
else: else:
text = autoconfig.read_text('utf-8') data = autoconfig.read()
lines = text.splitlines() lines = autoconfig.read_raw().splitlines()
if insert: if insert:
assert lines[0].startswith('# DO NOT edit this file by hand,') assert lines[0].startswith('# DO NOT edit this file by hand,')
assert 'config_version: {}'.format(yaml.VERSION) in lines
assert 'global:' in lines
print(lines) print(lines)
if 'magenta' in (old_config or ''): if old_config is not None:
assert ' colors.hints.fg: magenta' in lines assert data['colors.hints.fg'] == {'global': 'magenta'}
if insert: if insert:
assert ' tabs.show: never' in lines assert data['tabs.show'] == {'global': 'never'}
def test_init_save_manager(self, yaml, fake_save_manager): def test_init_save_manager(self, yaml, fake_save_manager):
yaml.init_save_manager(fake_save_manager) yaml.init_save_manager(fake_save_manager)
fake_save_manager.add_saveable.assert_called_with( fake_save_manager.add_saveable.assert_called_with(
'yaml-config', unittest.mock.ANY, unittest.mock.ANY) 'yaml-config', unittest.mock.ANY, unittest.mock.ANY)
def test_unknown_key(self, yaml, config_tmpdir): def test_unknown_key(self, yaml, autoconfig):
"""An unknown setting should show an error.""" """An unknown setting should show an error."""
autoconfig = config_tmpdir / 'autoconfig.yml' autoconfig.write({'hello': {'global': 'world'}})
autoconfig.write_text('global:\n hello: world', encoding='utf-8')
with pytest.raises(configexc.ConfigFileErrors) as excinfo: with pytest.raises(configexc.ConfigFileErrors) as excinfo:
yaml.load() yaml.load()
@ -127,10 +152,9 @@ class TestYaml:
assert error.text == "While loading options" assert error.text == "While loading options"
assert str(error.exception) == "Unknown option hello" assert str(error.exception) == "Unknown option hello"
def test_multiple_unknown_keys(self, yaml, config_tmpdir): def test_multiple_unknown_keys(self, yaml, autoconfig):
"""With multiple unknown settings, all should be shown.""" """With multiple unknown settings, all should be shown."""
autoconfig = config_tmpdir / 'autoconfig.yml' autoconfig.write({'one': {'global': 1}, 'two': {'global': 2}})
autoconfig.write_text('global:\n one: 1\n two: 2', encoding='utf-8')
with pytest.raises(configexc.ConfigFileErrors) as excinfo: with pytest.raises(configexc.ConfigFileErrors) as excinfo:
yaml.load() yaml.load()
@ -141,23 +165,21 @@ class TestYaml:
assert str(error1.exception) == "Unknown option one" assert str(error1.exception) == "Unknown option one"
assert str(error2.exception) == "Unknown option two" assert str(error2.exception) == "Unknown option two"
def test_deleted_key(self, monkeypatch, yaml, config_tmpdir): def test_deleted_key(self, monkeypatch, yaml, autoconfig):
"""A key marked as deleted should be removed.""" """A key marked as deleted should be removed."""
autoconfig = config_tmpdir / 'autoconfig.yml' autoconfig.write({'hello': {'global': 'world'}})
autoconfig.write_text('global:\n hello: world', encoding='utf-8')
monkeypatch.setattr(configdata.MIGRATIONS, 'deleted', ['hello']) monkeypatch.setattr(configdata.MIGRATIONS, 'deleted', ['hello'])
yaml.load() yaml.load()
yaml._save() yaml._save()
lines = autoconfig.read_text('utf-8').splitlines() data = autoconfig.read()
assert ' hello: world' not in lines assert not data
def test_renamed_key(self, monkeypatch, yaml, config_tmpdir): def test_renamed_key(self, monkeypatch, yaml, autoconfig):
"""A key marked as renamed should be renamed properly.""" """A key marked as renamed should be renamed properly."""
autoconfig = config_tmpdir / 'autoconfig.yml' autoconfig.write({'old': {'global': 'value'}})
autoconfig.write_text('global:\n old: value', encoding='utf-8')
monkeypatch.setattr(configdata.MIGRATIONS, 'renamed', monkeypatch.setattr(configdata.MIGRATIONS, 'renamed',
{'old': 'tabs.show'}) {'old': 'tabs.show'})
@ -165,29 +187,25 @@ class TestYaml:
yaml.load() yaml.load()
yaml._save() yaml._save()
lines = autoconfig.read_text('utf-8').splitlines() data = autoconfig.read()
assert ' old: value' not in lines assert data == {'tabs.show': {'global': 'value'}}
assert ' tabs.show: value' in lines
@pytest.mark.parametrize('persist', [True, False]) @pytest.mark.parametrize('persist', [True, False])
def test_merge_persist(self, yaml, config_tmpdir, persist): def test_merge_persist(self, yaml, autoconfig, persist):
"""Tests for migration of tabs.persist_mode_on_change.""" """Tests for migration of tabs.persist_mode_on_change."""
autoconfig = config_tmpdir / 'autoconfig.yml' autoconfig.write({'tabs.persist_mode_on_change': {'global': persist}})
autoconfig.write_text('global:\n tabs.persist_mode_on_change: {}'.
format(persist), encoding='utf-8')
yaml.load() yaml.load()
yaml._save() yaml._save()
lines = autoconfig.read_text('utf-8').splitlines() data = autoconfig.read()
assert 'tabs.persist_mode_on_change' not in data
mode = 'persist' if persist else 'normal' mode = 'persist' if persist else 'normal'
assert ' tabs.persist_mode_on_change:' not in lines assert data['tabs.mode_on_change'] == mode
assert ' tabs.mode_on_change: {}'.format(mode) in lines
def test_renamed_key_unknown_target(self, monkeypatch, yaml, def test_renamed_key_unknown_target(self, monkeypatch, yaml,
config_tmpdir): autoconfig):
"""A key marked as renamed with invalid name should raise an error.""" """A key marked as renamed with invalid name should raise an error."""
autoconfig = config_tmpdir / 'autoconfig.yml' autoconfig.write_text({'old': {'global': 'value'}})
autoconfig.write_text('global:\n old: value', encoding='utf-8')
monkeypatch.setattr(configdata.MIGRATIONS, 'renamed', monkeypatch.setattr(configdata.MIGRATIONS, 'renamed',
{'old': 'new'}) {'old': 'new'})
@ -202,7 +220,7 @@ class TestYaml:
@pytest.mark.parametrize('old_config', [ @pytest.mark.parametrize('old_config', [
None, None,
'global:\n colors.hints.fg: magenta', {'colors.hints.fg': {'global': 'magenta'}},
]) ])
@pytest.mark.parametrize('key, value', [ @pytest.mark.parametrize('key, value', [
('colors.hints.fg', 'green'), ('colors.hints.fg', 'green'),
@ -210,18 +228,18 @@ class TestYaml:
('confirm_quit', True), ('confirm_quit', True),
('confirm_quit', False), ('confirm_quit', False),
]) ])
def test_changed(self, yaml, qtbot, config_tmpdir, old_config, key, value): def test_changed(self, yaml, qtbot, autoconfig,
autoconfig = config_tmpdir / 'autoconfig.yml' old_config, key, value):
if old_config is not None: if old_config is not None:
autoconfig.write_text(old_config, 'utf-8') autoconfig.write(old_config)
yaml.load() yaml.load()
with qtbot.wait_signal(yaml.changed): with qtbot.wait_signal(yaml.changed):
yaml[key] = value yaml.set_obj(key, value)
assert key in yaml assert key in yaml
assert yaml[key] == value assert yaml._values[key].get_for_url(fallback=False) == value
yaml._save() yaml._save()
@ -229,42 +247,40 @@ class TestYaml:
yaml.load() yaml.load()
assert key in yaml assert key in yaml
assert yaml[key] == value assert yaml._values[key].get_for_url(fallback=False) == value
def test_iter(self, yaml): def test_iter(self, yaml):
yaml['foo'] = 23 yaml.set_obj('foo', 23)
yaml['bar'] = 42 yaml.set_obj('bar', 42)
assert list(iter(yaml)) == [('bar', 42), ('foo', 23)] assert list(iter(yaml)) == [('bar', 42), ('foo', 23)]
@pytest.mark.parametrize('old_config', [ @pytest.mark.parametrize('old_config', [
None, None,
'global:\n colors.hints.fg: magenta', {'colors.hints.fg': {'global': 'magenta'}},
]) ])
def test_unchanged(self, yaml, config_tmpdir, old_config): def test_unchanged(self, yaml, autoconfig, old_config):
autoconfig = config_tmpdir / 'autoconfig.yml'
mtime = None mtime = None
if old_config is not None: if old_config is not None:
autoconfig.write_text(old_config, 'utf-8') autoconfig.write(old_config)
mtime = autoconfig.stat().mtime mtime = autoconfig.fobj.stat().mtime
yaml.load() yaml.load()
yaml._save() yaml._save()
if old_config is None: if old_config is None:
assert not autoconfig.exists() assert not autoconfig.fobj.exists()
else: else:
assert autoconfig.stat().mtime == mtime assert autoconfig.fobj.stat().mtime == mtime
@pytest.mark.parametrize('line, text, exception', [ @pytest.mark.parametrize('line, text, exception', [
('%', 'While parsing', 'while scanning a directive'), ('%', 'While parsing', 'while scanning a directive'),
('global: 42', 'While loading data', "'global' object is not a dict"), ('settings: 42', 'While loading data', "'settings' object is not a dict"),
('foo: 42', 'While loading data', ('foo: 42', 'While loading data',
"Toplevel object does not contain 'global' key"), "Toplevel object does not contain 'settings' key"),
('42', 'While loading data', "Toplevel object is not a dict"), ('42', 'While loading data', "Toplevel object is not a dict"),
]) ])
def test_invalid(self, yaml, config_tmpdir, line, text, exception): def test_invalid(self, yaml, autoconfig, line, text, exception):
autoconfig = config_tmpdir / 'autoconfig.yml' autoconfig.write_raw(line)
autoconfig.write_text(line, 'utf-8', ensure=True)
with pytest.raises(configexc.ConfigFileErrors) as excinfo: with pytest.raises(configexc.ConfigFileErrors) as excinfo:
yaml.load() yaml.load()
@ -275,11 +291,10 @@ class TestYaml:
assert str(error.exception).splitlines()[0] == exception assert str(error.exception).splitlines()[0] == exception
assert error.traceback is None assert error.traceback is None
def test_oserror(self, yaml, config_tmpdir): def test_oserror(self, yaml, autoconfig):
autoconfig = config_tmpdir / 'autoconfig.yml' autoconfig.fobj.ensure()
autoconfig.ensure() autoconfig.fobj.chmod(0)
autoconfig.chmod(0) if os.access(str(autoconfig.fobj), os.R_OK):
if os.access(str(autoconfig), os.R_OK):
# Docker container or similar # Docker container or similar
pytest.skip("File was still readable") pytest.skip("File was still readable")
@ -292,22 +307,22 @@ class TestYaml:
assert isinstance(error.exception, OSError) assert isinstance(error.exception, OSError)
assert error.traceback is None assert error.traceback is None
def test_unset(self, yaml, qtbot, config_tmpdir): def test_unset(self, yaml, qtbot):
name = 'tabs.show' name = 'tabs.show'
yaml[name] = 'never' yaml.set_obj(name, 'never')
with qtbot.wait_signal(yaml.changed): with qtbot.wait_signal(yaml.changed):
yaml.unset(name) yaml.unset(name)
assert name not in yaml assert name not in yaml
def test_unset_never_set(self, yaml, qtbot, config_tmpdir): def test_unset_never_set(self, yaml, qtbot):
with qtbot.assert_not_emitted(yaml.changed): with qtbot.assert_not_emitted(yaml.changed):
yaml.unset('tabs.show') yaml.unset('tabs.show')
def test_clear(self, yaml, qtbot, config_tmpdir): def test_clear(self, yaml, qtbot):
name = 'tabs.show' name = 'tabs.show'
yaml[name] = 'never' yaml.set_obj(name, 'never')
with qtbot.wait_signal(yaml.changed): with qtbot.wait_signal(yaml.changed):
yaml.clear() yaml.clear()