Skip to content

Commit

Permalink
Added custom exceptions for each module (#11)
Browse files Browse the repository at this point in the history
* Created custom exceptions

* Fixed test errors. Added exceptions to code
  • Loading branch information
turulomio committed Dec 1, 2023
1 parent 9dbf468 commit 5fdcdb3
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 18 deletions.
25 changes: 14 additions & 11 deletions pydicts/casts.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from datetime import timedelta, date, datetime, time
from gettext import translation
from importlib.resources import files
from pydicts import exceptions
from zoneinfo import ZoneInfo

try:
Expand All @@ -21,11 +22,13 @@ def object_or_empty(v):

## Converts a string to a decimal
def str2decimal(s, type):
if s is None:
return None
if type==1: #2.123,25
try:
return Decimal(s.replace(".","").replace(",", "."))
except:
return None
raise exceptions.CastException(_("Method str2decimal couln't convert {0} ({1}) to a Decimal"))


def str2bool(value):
Expand All @@ -35,7 +38,7 @@ def str2bool(value):
@return Boolean
"""
def exception():
raise Exception(_("Method str2bool couldn't convert {0} ({1}) to a boolean").format(value, value.__class__))
raise exceptions.CastException(_("Method str2bool couldn't convert {0} ({1}) to a boolean").format(value, value.__class__))
if not value.__class__ is str:
exception()

Expand Down Expand Up @@ -183,7 +186,7 @@ def dtaware_day_end(dt, tz_name):
Returns the last datetime (microsecond level) of the day in tz_name zone
"""
if is_naive():
raise Exception(_("Datetime parameter should be aware"))
raise exceptions.CastException(_("A datetime with timezone is needed"))
dt=dtaware_changes_tz(dt, tz_name)
return dt.replace(hour=23, minute=59, second=59, microsecond=999999)

Expand All @@ -192,7 +195,7 @@ def dtnaive_day_end(dt):
Returns the last datetime (microsecond level) of the day in naive format
"""
if is_aware(dt):
raise Exception(_("Datetime parameter should be naive"))
raise exceptions.CastException(_("A datetime without timezone is needed"))
return dt.replace(hour=23, minute=59, second=59, microsecond=999999)

## Returns the end of the day dtnaive from a date
Expand All @@ -211,7 +214,7 @@ def dtnaive_day_start(dt):
## Returns a dtnaive or dtawre (as parameter) with the end of the day in zone tz_name
def dtaware_day_start(dt, tz_name):
if is_naive():
raise Exception(_("Datetime parameter should be aware"))
raise exceptions.CastException(_("A datetime with timezone is needed"))
dt=dtaware_changes_tz(dt, tz_name)
return dt.replace(hour=0, minute=0, second=0, microsecond=0)

Expand Down Expand Up @@ -277,7 +280,7 @@ def str2time(s, format="HH:MM"):
points=s.split(":")
return time(int(points[0]), int(points[1]))
else:
raise Exception(_("I can't convert this format '{}'. I only support this {}").format(format, allowed))
raise exceptions.CastException(_("I can't convert this format '{}'. I only support this {}").format(format, allowed))

## Converts a time to a string
def time2str(ti, format="HH:MM" ):
Expand Down Expand Up @@ -315,7 +318,7 @@ def str2date(iso, format="YYYY-MM-DD"):
except:
return None
else:
raise Exception(_("I can't convert this format '{}'. I only support this {}").format(format, allowed))
raise exceptions.CastException(_("I can't convert this format '{}'. I only support this {}").format(format, allowed))

def str2dtnaive(s, format):
allowed=["%Y%m%d%H%M","%Y-%m-%d %H:%M:%S","%d/%m/%Y %H:%M","%d %m %H:%M %Y","%Y-%m-%d %H:%M:%S.","%H:%M:%S", '%b %d %H:%M:%S']
Expand Down Expand Up @@ -344,7 +347,7 @@ def str2dtnaive(s, format):
s=f"{date.today().year} {s}"
return datetime.strptime(s, '%Y %b %d %H:%M:%S')
else:
raise Exception(_("I can't convert this format '{}'. I only support this {}").format(format, allowed))
raise exceptions.CastException(_("I can't convert this format '{}'. I only support this {}").format(format, allowed))

def str2dtaware(s, format, tz_name='UTC'):
allowed=["%Y-%m-%d %H:%M:%S%z","%Y-%m-%d %H:%M:%S.%z", "JsUtcIso"]
Expand Down Expand Up @@ -397,7 +400,7 @@ def epochmicros2dtaware(n, tz="UTC"):
## @return String
def dtaware2str(dt, format):
if is_naive(dt)==True:
raise Exception("A dtaware is needed for {}").format(dt)
raise exceptions.CastException("A datetime with timezone is needed for {}").format(dt)
else:
return dtnaive2str(dt, format)

Expand All @@ -421,7 +424,7 @@ def dtnaive2str(dt, format):
elif format=="JsUtcIso":
return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
else:
raise Exception(_("I can't convert this format '{}'. I only support this {}").format(format, allowed))
raise exceptions.CastException(_("I can't convert this format '{}'. I only support this {}").format(format, allowed))

## Changes zoneinfo from a dtaware object
## For example:
Expand All @@ -437,7 +440,7 @@ def dtaware_changes_tz(dt, tzname):
if is_aware(dt):
return dt.astimezone(ZoneInfo(tzname))
else:
raise Exception(_("Dtaware needed"))
raise exceptions.CastException(_("A datetime with timezone is needed"))

## Returns a list of tuples (year, month) from a month to another month, both included
## @param year_from Integer
Expand Down
14 changes: 14 additions & 0 deletions pydicts/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class LodException(Exception):
pass

class CastException(Exception):
pass

class LodXYVException(Exception):
pass

class LodYMVException(Exception):
pass

class LolException(Exception):
pass
5 changes: 3 additions & 2 deletions pydicts/lol.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from gettext import translation
from importlib.resources import files
from pydicts import exceptions

try:
t=translation('pydicts', files("pydicts") / 'locale')
Expand All @@ -14,7 +15,7 @@
## @param column List with the values to add. Must be of the same size of rows
def lol_add_column(rows, index, column):
if len(rows)!=len(column):
raise Exception(_("I can't add a column with different size of lol"))
raise exceptions.LolException(_("I can't add a column with different size of lol"))
r_rows=[]
for i, row in enumerate(rows):
r_rows.append(row[0:index] + [column[i],] + row[index:len(row)])
Expand All @@ -23,7 +24,7 @@ def lol_add_column(rows, index, column):
## Returns a list with object in positions removed
def list_remove_positions(l, listindex):
if l is None:
raise Exception(_("I can't remove positions from a None list"))
raise exceptions.LolException(_("I can't remove positions from a None list"))
return None
r=[]
for i, o in enumerate(l):
Expand Down
10 changes: 5 additions & 5 deletions pydicts/tests/test_casts.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import date, time, datetime
from decimal import Decimal
from pydicts import casts
from pydicts import casts, exceptions
from pytest import raises
from zoneinfo import ZoneInfo

Expand All @@ -19,11 +19,11 @@ def test_str2decimal():
assert casts.str2decimal("2.123,25", 1)==Decimal("2123.25")

def test_str2bool():
with raises(Exception):
with raises(exceptions.CastException):
casts.str2bool(None)==None
with raises(Exception):
with raises(exceptions.CastException):
assert casts.str2bool(1)==True
with raises(Exception):
with raises(exceptions.CastException):
assert casts.str2bool(0)==False
assert casts.str2bool("true")==True
assert casts.str2bool("True")==True
Expand Down Expand Up @@ -255,5 +255,5 @@ def test_dtaware_changes_tz():

def test_months():
assert casts.months(2023, 11, 2024, 1)== [(2023, 11), (2023, 12), (2024, 1)]
assert casts.months(2023, 9)== [(2023, 9), (2023, 10), (2023, 11)]
assert casts.months(2023, 9, 2023, 9)== [(2023, 9)]

0 comments on commit 5fdcdb3

Please sign in to comment.