Skip to content

Commit

Permalink
Merge pull request #13 from ShadowXBoss696/build-unit-test-cases
Browse files Browse the repository at this point in the history
Wrote pytests for settings module
  • Loading branch information
ShadowXBoss696 authored Apr 18, 2024
2 parents 4bcaa06 + 5cdc662 commit f0a5ca2
Show file tree
Hide file tree
Showing 3 changed files with 114 additions and 24 deletions.
44 changes: 25 additions & 19 deletions fastboot/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@

DEVELOP: bool = PROJECT_CONFIG_TOML.exists()


# ---------------------------------------------------------------------------------

PREF_DEF_REGISTRY: list[type["Preference"]] = []
Expand All @@ -31,7 +30,7 @@ def __getattr__(self, name: str) -> Any:
return self._store[name].get_value()

def __setattr__(self, name: str, value: Any) -> None:
if name in self._store:
if name != "_store" and name in self._store:
self._store[name].set_value(value)
else:
super().__setattr__(name, value)
Expand All @@ -52,6 +51,8 @@ def __str__(self) -> str:

return os.linesep.join(lines)

__repr__ = __str__


class Preference(metaclass=ABCMeta):
"""
Expand Down Expand Up @@ -82,6 +83,10 @@ def __init_subclass__(cls, **kwargs):
if not hasattr(cls, attr_key):
raise TypeError(f"Attribute '{attr_key}' missing for class {cls.__name__}")

# Wrap validator with staticmethod annotation
if cls.validator:
cls.validator = staticmethod(cls.validator)

# Register the settings
PREF_DEF_REGISTRY.append(cls)

Expand All @@ -99,20 +104,21 @@ def __repr__(self):

# ---------------------------------------------------------------------------------


class WorkerCount(Preference):
# TODO: This is for demo only

name = "worker"
default = 1
desc = """\
The number of worker processes for handling requests.
A positive integer generally in the ``2-4 x $(NUM_CORES)`` range.
You'll want to vary this a bit to find the best for your particular
application's work load.
By default, the value of the ``WEB_CONCURRENCY`` environment variable,
which is set by some Platform-as-a-Service providers such as Heroku. If
it is not defined, the default is ``1``.
"""
#
# === For Demo Only ===
#
# class WorkerCount(Preference):
#
# name = "worker"
# default = 1
# desc = """\
# The number of worker processes for handling requests.
#
# A positive integer generally in the ``2-4 x $(NUM_CORES)`` range.
# You'll want to vary this a bit to find the best for your particular
# application's work load.
#
# By default, the value of the ``WEB_CONCURRENCY`` environment variable,
# which is set by some Platform-as-a-Service providers such as Heroku. If
# it is not defined, the default is ``1``.
# """
10 changes: 5 additions & 5 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

84 changes: 84 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import pytest

from fastboot.settings import PREF_DEF_REGISTRY, AppPreferences, Preference

# ---------------------------
# Module Level Setup/TearDown
# ---------------------------


def setup_module(module) -> None:
"""Setup any state specific to the execution of the given module."""

# Define dummy validators

def text_is_not_empty(value: str) -> None:
"""Assert that the given string is not empty."""

# Assert value is string
if not isinstance(value, str):
raise TypeError(f"Invalid value type passed. Expected: 'str', Found: '{value.__class__.__name__}'")

# Assert value is not empty
if len(value.strip()) == 0:
raise ValueError("Empty string passed")

# Define dummy preferences
class DummyPreference(Preference):
name = "dummy_pref"
desc = """\
This is a dummy preference for testing purposes.
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
"""
default = "default_value"
validator = text_is_not_empty


def teardown_module(module):
"""teardown any state that was previously setup with a setup_module method."""

# Remove dummy registered preferences
PREF_DEF_REGISTRY[:] = [pref for pref in PREF_DEF_REGISTRY if pref.__class__.__name__ not in ["DummyPreference"]]


@pytest.fixture
def preferences() -> AppPreferences:
yield AppPreferences()


def test_prefs_are_registered() -> None:
"""Test if the preferences are registered properly or not"""

# At least one preference must be registered
assert len(PREF_DEF_REGISTRY) > 0, "No preference registered"


def test_app_preference_getter_and_setters(preferences: AppPreferences):
"""Test if getting and setting preference is properly working or not."""

# Test default value
assert (
preferences.dummy_pref == "default_value"
), f"Default value mismatch. Expected: 'default_value', Found: {preferences.dummy_pref}"

# Test setting and getting new value
preferences.dummy_pref = "new_value"

assert (
preferences.dummy_pref == "new_value"
), f"New value mismatch. Expected: 'new_value', Found: {preferences.dummy_pref}"


def test_print_app_preference(preferences: AppPreferences) -> None:
"""Test app preference values are printed correctly."""

output: str = repr(preferences)
print(output)

assert len(output) > 0, "No output printed"
assert "dummy_pref" in output, "Dummy preference value is not printed correctly"

0 comments on commit f0a5ca2

Please sign in to comment.