Skip to content

Commit

Permalink
Merge pull request #101 from eoyilmaz/93-increase-test-coverage
Browse files Browse the repository at this point in the history
93 increase test coverage
  • Loading branch information
eoyilmaz authored Nov 8, 2024
2 parents 72b6dfc + 28b729d commit c9d1245
Show file tree
Hide file tree
Showing 94 changed files with 2,890 additions and 1,139 deletions.
19 changes: 9 additions & 10 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,21 @@ install:

clean: FORCE
@printf "\n\033[36m--- $@: Clean ---\033[0m\n"
-rm -rf .pytest_cache
-rm -f .coverage.*
-rm -rf dist
-rm -rf build
-rm -rf docs/build
-rm -rf docs/source/generated/*
-rm -Rf .pytest_cache
-rm -f .coverage*
-rm -Rf dist
-rm -Rf build
-rm -Rf docs/build
-rm -Rf docs/source/generated/*
-rm -Rf htmlcov

clean-all: clean
@printf "\n\033[36m--- $@: Clean All---\033[0m\n"
-rm -f INSTALLED_FILES
-rm -f setuptools-*.egg
-rm -f use-distutils
-rm -f .coverage*
-rm -Rf .tox
-rm -Rf htmlcov
-rm -rf dist
-rm -Rf dist
-rm -Rf src/$(PACKAGE_NAME).egg-info
-rm -Rf $(VIRTUALENV_DIR)

Expand Down Expand Up @@ -83,7 +82,7 @@ tests:
echo -e "\n\033[36m--- $@: Using virtualenv at '$(VIRTUALENV_DIR)' ---\033[0m\n";
source ./$(VIRTUALENV_DIR)/bin/activate; \
echo -e "\n\033[36m--- $@: Using python interpretter '`which python`' ---\033[0m\n"; \
PYTHONPATH=src pytest -v -n auto -W ignore --color=yes --cov=src --cov-report term --cov-fail-under 99 tests;
PYTHONPATH=src pytest -n auto -W ignore --color=yes --cov=src --cov-report term --cov-report html --cov-append --cov-fail-under 99 tests;

.PHONY: docs
docs:
Expand Down
3 changes: 2 additions & 1 deletion examples/extending/great_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class GreatEntity(SimpleEntity, ReferenceMixin):
"""The new great entity class, which is a new simpleEntity with ReferenceMixin."""

__tablename__ = "GreatEntities"
__mapper_args__ = {"polymorphic_identity": "GreatEntity"}
great_entity_id = Column(
"id", Integer, ForeignKey("SimpleEntities.c.id"), primary_key=True
"id", Integer, ForeignKey("SimpleEntities.id"), primary_key=True
)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ universal = false

[tool.pytest.ini_options]
pythonpath = ["."]
addopts = "-n auto -W ignore --color=yes --cov --cov-report html tests"
addopts = "-n auto -W ignore --color=yes --cov=src --cov-report term --cov-report html --cov-append tests"

[tool.black]

Expand Down
1 change: 1 addition & 0 deletions src/stalker/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"""
from stalker.version import __version__ # noqa: F401
from stalker import config, log # noqa: I100

if True:
defaults = config.Config()
from stalker.models.asset import Asset
Expand Down
3 changes: 0 additions & 3 deletions src/stalker/db/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,6 @@ def update_defaults_with_studio():
Update only if a database and a Studio instance is present.
"""
if not DBSession:
return

with DBSession.no_autoflush:
studio = Studio.query.first()
# studio = DBSession.query(Studio).first()
Expand Down
2 changes: 1 addition & 1 deletion src/stalker/db/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def process_result_value(self, value, dialect):
"""Process result value.
Args:
value (str): The str reprsentation of the JSON data.
value (str): The str representation of the JSON data.
dialect (str): The dialect.
Returns:
Expand Down
6 changes: 1 addition & 5 deletions src/stalker/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,7 @@ def set_level(level):
)
)

try:
level_names = logging._levelToName
except AttributeError:
# Python 2
level_names = logging._levelNames
level_names = logging._levelToName

if level not in level_names:
raise ValueError(
Expand Down
40 changes: 11 additions & 29 deletions src/stalker/models/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,11 @@ class Permission(Base):
access (str): An Enum value which can have the one of the values of
``Allow`` or ``Deny``.
action (str): An Enum value from the list ['Create', 'Read', 'Update',
'Delete', 'List']. Can not be None. The list can be changed from
'Delete', 'List']. Cannot be None. The list can be changed from
stalker.config.Config.default_actions.
class_name (str): The name of the class that this action is applied
to. Can not be None or an empty string.
to. Cannot be None or an empty string.
"""

__tablename__ = "Permissions"
Expand Down Expand Up @@ -393,7 +393,7 @@ class User(Entity, ACLMixin):
format.
login (str): This is the login name of the user, it should be all lower
case. Giving a string that has uppercase letters, it will be converted
to lower case. It can not be an empty string or None and it can not
to lower case. It cannot be an empty string or None and it cannot
contain any white space inside.
departments (List[Department]): It is the departments that the user is
a part of. It should be a list of Department objects. One user can
Expand Down Expand Up @@ -463,7 +463,7 @@ class User(Entity, ACLMixin):
unique=True,
doc="""The login name of the user.
Can not be empty.
Cannot be empty.
""",
)

Expand Down Expand Up @@ -648,14 +648,14 @@ def _validate_login(self, key, login):
str: The validated and formatted login value.
"""
if login is None:
raise TypeError(f"{self.__class__.__name__}.login can not be None")
raise TypeError(f"{self.__class__.__name__}.login cannot be None")

login = self._format_login(login)

# raise a ValueError if the login is an empty string after formatting
if login == "":
raise ValueError(
f"{self.__class__.__name__}.login can not be an empty string"
f"{self.__class__.__name__}.login cannot be an empty string"
)

logger.debug(f"name out: {login}")
Expand Down Expand Up @@ -780,7 +780,7 @@ def _validate_password(self, key, password):

if password == "":
raise ValueError(
f"{self.__class__.__name__}.password can not be an empty string"
f"{self.__class__.__name__}.password cannot be an empty string"
)

# mangle the password
Expand Down Expand Up @@ -1036,26 +1036,6 @@ def __init__(self):
self.session_data = None
self.load()

@classmethod
def default_json_serializer(cls, obj):
"""Convert the given object to JSON serializable format.
This is the default serializer for json data
Args:
obj (Union[datetime.datetime, User, int]): Either a ``datetime.datetime``
or :class:`.User` or an int value.
Returns:
int: The int correspondence of the given data.
"""
if isinstance(obj, datetime.datetime):
return cls.datetime_to_millis(obj)
elif isinstance(obj, User):
return User.id
elif isinstance(obj, int):
return obj

@classmethod
def datetime_to_millis(cls, dt):
"""Calculate the milliseconds since epoch for the given datetime value.
Expand Down Expand Up @@ -1128,8 +1108,10 @@ def save(self):
self.valid_to = datetime.datetime.now(pytz.utc) + datetime.timedelta(days=10)
# serialize self
dumped_data = json.dumps(
{"valid_to": self.valid_to, "logged_in_user_id": self.logged_in_user_id},
default=self.default_json_serializer,
{
"valid_to": self.datetime_to_millis(self.valid_to),
"logged_in_user_id": self.logged_in_user_id,
},
)
logger.debug(f"dumped session data : {dumped_data}")
self._write_data(dumped_data)
Expand Down
6 changes: 3 additions & 3 deletions src/stalker/models/budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,8 +518,8 @@ class Invoice(Entity, AmountMixin, UnitMixin):
invoice.
budget (Budget): The :class:`.Budget` instance that owns this invoice.
amount (Union[int, float]): The amount of this invoice. Without the
:attr:`.Invoice.unit` attribute it is meaningless. This can not be skipped.
unit (str): The unit of the issued amount. This can not be skipped.
:attr:`.Invoice.unit` attribute it is meaningless. This cannot be skipped.
unit (str): The unit of the issued amount. This cannot be skipped.
"""

__auto_name__ = True
Expand Down Expand Up @@ -612,7 +612,7 @@ class Payment(Entity, AmountMixin, UnitMixin):
Args:
invoice (Invoice): The :class:`.Invoice` instance that this payment is related
to. This can not be skipped.
to. This cannot be skipped.
"""

__auto_name__ = True
Expand Down
20 changes: 11 additions & 9 deletions src/stalker/models/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,14 @@ class SimpleEntity(Base):
For derived classes if the
:attr:`.SimpleEntity.type` needed to be specifically specified, that is
it can not be None or nothing else then a :class:`.Type` instance, set
it cannot be None or nothing else then a :class:`.Type` instance, set
the ``strictly_typed`` class attribute to True::
class NewClass(SimpleEntity):
__strictly_typed__ = True
This will ensure that the derived class always have a proper
:attr:`.SimpleEntity.type` attribute and can not be initialized without
:attr:`.SimpleEntity.type` attribute and cannot be initialized without
one.
Two SimpleEntities considered to be equal if they have the same
Expand Down Expand Up @@ -295,7 +295,7 @@ def __hash__(self):
Returns:
int: The hash value.
"""
return hash(self.id) + 2 * hash(self.name) + 3 * hash(self.entity_type)
return hash("{}:{}:{}".format(self.id, self.name, self.entity_type))

@validates("description")
def _validate_description(self, key, description):
Expand Down Expand Up @@ -374,7 +374,7 @@ def _validate_name(self, key, name):

# it is None
if name is None:
raise TypeError(f"{self.__class__.__name__}.name can not be None")
raise TypeError(f"{self.__class__.__name__}.name cannot be None")

if not isinstance(name, string_types):
raise TypeError(
Expand All @@ -387,7 +387,7 @@ def _validate_name(self, key, name):
# it is empty
if name == "":
raise ValueError(
f"{self.__class__.__name__}.name can not be an empty string"
f"{self.__class__.__name__}.name cannot be an empty string"
)

# also set the nice_name
Expand Down Expand Up @@ -534,7 +534,7 @@ def _validate_date_created(self, key, date_created):
datetime.datetime: The validated date_created value.
"""
if date_created is None:
raise TypeError(f"{self.__class__.__name__}.date_created can not be None")
raise TypeError(f"{self.__class__.__name__}.date_created cannot be None")

if not isinstance(date_created, datetime.datetime):
raise TypeError(
Expand Down Expand Up @@ -563,7 +563,7 @@ def _validate_date_updated(self, key, date_updated):
"""
# it is None
if date_updated is None:
raise TypeError(f"{self.__class__.__name__}.date_updated can not be None")
raise TypeError(f"{self.__class__.__name__}.date_updated cannot be None")

# it is not a datetime.datetime instance
if not isinstance(date_updated, datetime.datetime):
Expand Down Expand Up @@ -890,8 +890,10 @@ def __eq__(self, other):
bool: True if the other is also a EntityGroup instance and has the same
attribute values.
"""
return super(SimpleEntity, self).__eq__(other) and isinstance(
other, EntityGroup
return (
super(SimpleEntity, self).__eq__(other)
and isinstance(other, EntityGroup)
and self.entities == other.entities
)

def __hash__(self):
Expand Down
8 changes: 4 additions & 4 deletions src/stalker/models/link.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,8 @@ def _format_path(path):
Returns:
str: The formatted path value.
"""
if not isinstance(path, string_types):
path = path.encode("utf-8")
if isinstance(path, bytes):
path = path.decode("utf-8")

return path.replace("\\", "/")

Expand All @@ -167,7 +167,7 @@ def path(self, path):
ValueError: If the given path is an empty str.
"""
if path is None:
raise TypeError(f"{self.__class__.__name__}.path can not be set to None")
raise TypeError(f"{self.__class__.__name__}.path cannot be set to None")

if not isinstance(path, string_types):
raise TypeError(
Expand All @@ -177,7 +177,7 @@ def path(self, path):

if path == "":
raise ValueError(
f"{self.__class__.__name__}.path can not be an empty string"
f"{self.__class__.__name__}.path cannot be an empty string"
)

self.full_path = self._format_path(os.path.join(path, self.filename))
Expand Down
Loading

0 comments on commit c9d1245

Please sign in to comment.