Skip to content

Commit

Permalink
fix all ruff & mypy warnings and errors
Browse files Browse the repository at this point in the history
Signed-off-by: Grant Ramsay <seapagan@gmail.com>
  • Loading branch information
seapagan committed Oct 28, 2023
1 parent 9e1f6a6 commit 7755814
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 49 deletions.
6 changes: 1 addition & 5 deletions simple_toml_settings/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,10 @@
class SettingsError(Exception):
"""Base exception for settings errors."""

pass


class SettingsNotFound(SettingsError):
class SettingsNotFoundError(SettingsError):
"""The Settings file has not been found.
This will be raised if the settings file is not found and auto_create is
False.
"""

pass
29 changes: 18 additions & 11 deletions simple_toml_settings/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@

from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, Set
from typing import Any

import rtoml

from simple_toml_settings.exceptions import SettingsNotFound
from simple_toml_settings.exceptions import SettingsNotFoundError


@dataclass
Expand All @@ -31,7 +31,7 @@ class TOMLSettings:
# the schema_version is used to track changes to the settings file.
schema_version: str = "none"

_ignored_attrs: Set[str] = field(
_ignored_attrs: set[str] = field(
default_factory=lambda: {
"app_name",
"settings_folder",
Expand Down Expand Up @@ -62,9 +62,8 @@ def __post_create_hook__(self) -> None:
The save() method IS called after we run this automatically, it should
never be called manually.
"""
pass

def get_attrs(self) -> Dict[str, str]:
def get_attrs(self) -> dict[str, str]:
"""Return a dictionary of our setting values."""
return {
a: getattr(self, a)
Expand Down Expand Up @@ -92,22 +91,30 @@ def load(self) -> None:
self.__post_create_hook__()
self.save()
else:
raise SettingsNotFound(
"Cant find a Config File, please create one."
) from exc
message = "Cant find a Config File, please create one."
raise SettingsNotFoundError(message) from exc
return

for key, value in settings[self.app_name].items():
setattr(self, key, value)

def get(self, key: str) -> Any:
def get(
self,
key: str,
) -> Any: # noqa: ANN401
"""Get a setting by key."""
try:
return getattr(self, key)
except AttributeError:
return None

def set(self, key: str, value: str, autosave: bool = True) -> None:
def set( # noqa: A003
self,
key: str,
value: str,
*,
autosave: bool = True,
) -> None:
"""Set a setting by key and value.
If autosave is True (the default), the settings will be saved to the
Expand All @@ -117,6 +124,6 @@ def set(self, key: str, value: str, autosave: bool = True) -> None:
if autosave:
self.save()

def list_settings(self) -> Dict[str, str]:
def list_settings(self) -> dict[str, str]:
"""Return a dictionary of settings."""
return self.get_attrs()
1 change: 1 addition & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# noqa: D104
10 changes: 4 additions & 6 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@
from simple_toml_settings.settings import TOMLSettings


class TestSettings(TOMLSettings):
class SettingsExample(TOMLSettings):
"""Define a class for testing the Settings class."""

test_string_var: str = "test_value"
test_int_var: int = 42


@pytest.fixture()
def settings(fs):
def settings(fs) -> SettingsExample:
"""Return a Settings object for testing.
This fixture creates a fake home directory in a virtual filesystem. It then
Expand All @@ -24,7 +24,5 @@ def settings(fs):
# Create a fake home directory for the test
fs.create_dir(Path.home())

# Create a Settings object for the test
settings = TestSettings("test_app")

return settings
# Create and return a Settings object for the test
return SettingsExample("test_app")
60 changes: 33 additions & 27 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,31 @@

import pytest

from simple_toml_settings.exceptions import SettingsNotFound
from simple_toml_settings.exceptions import SettingsNotFoundError
from simple_toml_settings.settings import TOMLSettings

from .conftest import SettingsExample

def test_config_file_auto_created(settings):
TEST_APP_NAME = "test_app"


def test_config_file_auto_created(settings) -> None:
"""Test that the settings file is created if it doesn't exist."""
assert settings.settings_folder.exists()
assert settings.settings_folder.is_dir()
assert settings.settings_folder.name == ".test_app"
assert settings.settings_folder.name == f".{TEST_APP_NAME}"
assert settings.settings_file_name == "config.toml"


def test_exception_raised_on_missing_config_if_auto_create_is_false(fs):
def test_exception_raised_on_missing_config_if_auto_create_is_false(fs) -> None:
"""Test that the settings file is not created if auto_create is False."""
fs.create_dir(Path.home())

with pytest.raises(SettingsNotFound):
with pytest.raises(SettingsNotFoundError):
TOMLSettings("test_app", auto_create=False)


def test_local_config(fs):
def test_local_config(fs) -> None:
"""Test that local_config loads settings from the local directory."""
fs.create_file(
"config.toml",
Expand All @@ -33,7 +38,7 @@ def test_local_config(fs):
assert settings.get("test_string_var") == "local_app"


def test_post_create_hook_is_called(fs, mocker):
def test_post_create_hook_is_called(fs, mocker) -> None:
"""Test that the post_create_hook is called after settings file created."""
fs.create_dir(Path.home())

Expand All @@ -43,68 +48,69 @@ def test_post_create_hook_is_called(fs, mocker):
assert settings.__post_create_hook__.called


def test_get_attrs(settings):
def test_get_attrs(settings) -> None:
"""Test that we can get the attributes of the settings object."""
attrs = settings.get_attrs()
assert attrs["schema_version"] == "none"
assert attrs["test_string_var"] == "test_value"
assert attrs["test_int_var"] == 42
assert attrs["test_string_var"] == SettingsExample.test_string_var
assert attrs["test_int_var"] == SettingsExample.test_int_var


def test_get(settings):
def test_get(settings) -> None:
"""Test we can get settings."""
assert settings.get("app_name") == "test_app"
assert settings.get("nonexistent_key") is None
assert settings.get("test_string_var") == "test_value"
assert settings.get("test_int_var") == 42
assert settings.get("app_name") == TEST_APP_NAME
assert settings.get("test_string_var") == SettingsExample.test_string_var
assert settings.get("test_int_var") == SettingsExample.test_int_var


def test_set(settings):
def test_set(settings) -> None:
"""Test that a setting can be set."""
settings.set("app_name", "new_test_app")
assert settings.get("app_name") == "new_test_app"


def test_add_and_list_setting(settings):
def test_add_and_list_setting(settings) -> None:
"""Add a new setting and list all settings."""
settings.set("new_key", "new_value")
settings_dict = settings.list_settings()
assert settings_dict["new_key"] == "new_value"


def test_load_settings(settings):
def test_load_settings(settings) -> None:
"""Test that settings are loaded from the settings file."""
settings.load()
# length is 3 because of the 'schema' setting
assert len(settings.list_settings()) == 3
assert len(settings.list_settings()) == 3 # noqa: PLR2004

assert settings.get("schema_version") == "none"
assert settings.list_settings()["test_string_var"] == "test_value"
assert settings.list_settings()["test_int_var"] == 42
assert (
settings.list_settings()["test_int_var"] == SettingsExample.test_int_var
)


def test_set_schema_version(settings):
def test_set_schema_version(settings) -> None:
"""Test that the schema_version can be set using the 'set' method."""
settings.set("schema_version", "1.0.0")
settings.load()
assert settings.get("schema_version") == "1.0.0"


def test_autosave(settings):
def test_autosave(settings) -> None:
"""Test that settings are auto saved when autosave is True."""
settings.set("test_string_var", "new_value")
settings.load()
assert settings.get("test_string_var") == "new_value"


def test_no_autosave(settings):
def test_no_autosave(settings) -> None:
"""Test that settings are not auto saved when autosave is False."""
settings.set("test_string_var", "new_value", autosave=False)
settings.load()
assert settings.get("test_string_var") == "test_value"


def test_custom_file_name(fs):
def test_custom_file_name(fs) -> None:
"""Test that the settings file name can be customized."""
custom_file_name = "custom_config.toml"

Expand All @@ -114,13 +120,13 @@ def test_custom_file_name(fs):
assert (Path.home() / ".test_app" / custom_file_name).exists()

assert settings.settings_file_name == custom_file_name
assert settings.settings_folder.name == ".test_app"
assert settings.settings_folder.name == f".{TEST_APP_NAME}"
assert settings.settings_folder / settings.settings_file_name


def test_items_on_ignored_attrs(settings):
def test_items_on_ignored_attrs(settings) -> None:
"""Test that the ignored attributes are not returned by items()."""
list_settings = settings.list_settings()

for setting in settings._ignored_attrs:
for setting in settings._ignored_attrs: # noqa: SLF001
assert setting not in list_settings

0 comments on commit 7755814

Please sign in to comment.