Skip to content

Commit

Permalink
Replace "ValueError" with "TypeError" for invalid method args
Browse files Browse the repository at this point in the history
  • Loading branch information
Delgan committed Nov 1, 2019
1 parent 82bbf54 commit 361b448
Show file tree
Hide file tree
Showing 14 changed files with 87 additions and 56 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
- Prevent hypothetical ``ImportError`` if a Python installation is missing the built-in ``distutils`` module (`#118 <https://github.com/Delgan/loguru/issues/118>`_).
- Add the possibility to convert ``datetime`` to UTC before formatting (in logs and filenames) by adding ``"!UTC"`` at the end of the time format specifier (`#128 <https://github.com/Delgan/loguru/issues/128>`_).
- Add the level ``name`` as the first argument of namedtuple returned by the ``.level()`` method.
- Replace ``ValueError`` with ``TypeError`` for exceptions raised when a ``logger`` method was called with argument of invalid type.


`0.3.2`_ (2019-07-21)
Expand Down
6 changes: 3 additions & 3 deletions loguru/_file_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ def _make_rotation_function(rotation):
elif callable(rotation):
return rotation
else:
raise ValueError(
raise TypeError(
"Cannot infer rotation for objects of type: '%s'" % type(rotation).__name__
)

Expand All @@ -247,7 +247,7 @@ def _make_retention_function(retention):
elif callable(retention):
return retention
else:
raise ValueError(
raise TypeError(
"Cannot infer retention for objects of type: '%s'" % type(retention).__name__
)

Expand Down Expand Up @@ -313,7 +313,7 @@ def _make_compression_function(compression):
elif callable(compression):
return compression
else:
raise ValueError(
raise TypeError(
"Cannot infer compression for objects of type: '%s'" % type(compression).__name__
)

Expand Down
24 changes: 12 additions & 12 deletions loguru/_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -764,7 +764,7 @@ def add(
terminator = "\n"
exception_prefix = ""
else:
raise ValueError("Cannot log to objects of type '%s'." % type(sink).__name__)
raise TypeError("Cannot log to objects of type '%s'." % type(sink).__name__)

if filter is None:
filter_func = None
Expand All @@ -777,7 +777,7 @@ def add(
elif callable(filter):
filter_func = filter
else:
raise ValueError(
raise TypeError(
"Invalid filter, it should be a function or a string, not: '%s'"
% type(filter).__name__
)
Expand All @@ -787,7 +787,7 @@ def add(
elif isinstance(level, int):
levelno = level
else:
raise ValueError(
raise TypeError(
"Invalid level, it should be an integer or a string, not: '%s'"
% type(level).__name__
)
Expand All @@ -811,7 +811,7 @@ def add(
formatter = format
is_formatter_dynamic = True
else:
raise ValueError(
raise TypeError(
"Invalid format, it should be a string or a function, not: '%s'"
% type(format).__name__
)
Expand Down Expand Up @@ -881,7 +881,7 @@ def remove(self, handler_id=None):
>>> logger.info("No longer logging")
"""
if not (handler_id is None or isinstance(handler_id, int)):
raise ValueError(
raise TypeError(
"Invalid handler id, it should be an integer as returned "
"by the 'add()' method (or None), not: '%s'" % type(handler_id).__name__
)
Expand Down Expand Up @@ -1277,7 +1277,7 @@ def level(self, name, no=None, color=None, icon=None):
30 /!\\ Updated!
"""
if not isinstance(name, str):
raise ValueError(
raise TypeError(
"Invalid level name, it should be a string, not: '%s'" % type(name).__name__
)

Expand Down Expand Up @@ -1308,7 +1308,7 @@ def level(self, name, no=None, color=None, icon=None):
icon = old_icon

if not isinstance(no, int):
raise ValueError(
raise TypeError(
"Invalid level no, it should be an integer, not: '%s'" % type(no).__name__
)

Expand Down Expand Up @@ -1463,7 +1463,7 @@ def configure(self, *, handlers=None, levels=None, extra=None, patch=None, activ

def _change_activation(self, name, status):
if not (name is None or isinstance(name, str)):
raise ValueError(
raise TypeError(
"Invalid name, it should be a string (or None), not: '%s'" % type(name).__name__
)

Expand Down Expand Up @@ -1557,7 +1557,7 @@ def parse(file, pattern, *, cast={}, chunk=2 ** 16):
should_close = False
fileobj = file
else:
raise ValueError(
raise TypeError(
"Invalid file, it should be a string path or a file object, not: '%s'"
% type(file).__name__
)
Expand All @@ -1572,14 +1572,14 @@ def cast_function(groups):
elif callable(cast):
cast_function = cast
else:
raise ValueError(
raise TypeError(
"Invalid cast, it should be a function or a dict, not: '%s'" % type(cast).__name__
)

try:
regex = re.compile(pattern)
except TypeError:
raise ValueError(
raise TypeError(
"Invalid pattern, it should be a string or a compiled regex, not: '%s'"
% type(pattern).__name__
) from None
Expand Down Expand Up @@ -1784,7 +1784,7 @@ def _dynamic_level(level):
)
return (None, level)

raise ValueError(
raise TypeError(
"Invalid level, it should be an integer or a string, not: '%s'" % type(level).__name__
)

Expand Down
4 changes: 2 additions & 2 deletions tests/test_activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,11 @@ def test_f_globals_name_absent_with_others(writer, f_globals_name_absent):

@pytest.mark.parametrize("name", [42, [], object()])
def test_invalid_enable_name(name):
with pytest.raises(ValueError):
with pytest.raises(TypeError):
logger.enable(name)


@pytest.mark.parametrize("name", [42, [], object()])
def test_invalid_disable_name(name):
with pytest.raises(ValueError):
with pytest.raises(TypeError):
logger.disable(name)
2 changes: 1 addition & 1 deletion tests/test_add_option_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,5 @@ def test_filtered_in_f_globals_name_absent(writer, filter, f_globals_name_absent

@pytest.mark.parametrize("filter", [-1, 3.4, object()])
def test_invalid_filter(writer, filter):
with pytest.raises(ValueError):
with pytest.raises(TypeError):
logger.add(writer, filter=filter)
2 changes: 1 addition & 1 deletion tests/test_add_option_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def test_function_format_with_exception(writer):

@pytest.mark.parametrize("format", [-1, 3.4, object()])
def test_invalid_format(writer, format):
with pytest.raises(ValueError):
with pytest.raises(TypeError):
logger.add(writer, format=format)


Expand Down
8 changes: 7 additions & 1 deletion tests/test_add_option_level.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@ def test_level_too_high(writer, level):
assert writer.read() == ""


@pytest.mark.parametrize("level", ["foo", -1, 3.4, object()])
@pytest.mark.parametrize("level", [3.4, object()])
def test_invalid_level(writer, level):
with pytest.raises(TypeError):
logger.add(writer, level=level)


@pytest.mark.parametrize("level", ["foo", -1])
def test_unknown_level(writer, level):
with pytest.raises(ValueError):
logger.add(writer, level=level)
2 changes: 1 addition & 1 deletion tests/test_add_sinks.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def test_disabled_logger_in_sink(sink_with_logger):

@pytest.mark.parametrize("sink", [123, sys, object(), int])
def test_invalid_sink(sink):
with pytest.raises(ValueError):
with pytest.raises(TypeError):
log(sink, "")


Expand Down
8 changes: 7 additions & 1 deletion tests/test_filesink_compression.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,14 @@ def creation_time(filepath):
assert tmpdir.join("test.2018-01-01_00-00-00_000000.log.tar.gz").check(exists=1)


@pytest.mark.parametrize("compression", [0, True, os, object(), {"zip"}, "rar", ".7z", "tar.zip"])
@pytest.mark.parametrize("compression", [0, True, os, object(), {"zip"}])
def test_invalid_compression(compression):
with pytest.raises(TypeError):
logger.add("test.log", compression=compression)


@pytest.mark.parametrize("compression", ["rar", ".7z", "tar.zip"])
def test_unknown_compression(compression):
with pytest.raises(ValueError):
logger.add("test.log", compression=compression)

Expand Down
23 changes: 8 additions & 15 deletions tests/test_filesink_retention.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,22 +176,15 @@ def test_no_renaming(tmpdir):
assert tmpdir.join("test.log").read() == "test\n"


@pytest.mark.parametrize("retention", [datetime.time(12, 12, 12), os, object()])
def test_invalid_retention(retention):
with pytest.raises(TypeError):
logger.add("test.log", retention=retention)


@pytest.mark.parametrize(
"retention",
[
"W5",
"monday at 14:00",
"sunday",
"nope",
"5 MB",
"3 hours 2 dayz",
"d",
"H",
datetime.time(12, 12, 12),
os,
object(),
],
"retention", ["W5", "monday at 14:00", "sunday", "nope", "5 MB", "3 hours 2 dayz", "d", "H"]
)
def test_invalid_retention(retention):
def test_unkown_retention(retention):
with pytest.raises(ValueError):
logger.add("test.log", retention=retention)
15 changes: 9 additions & 6 deletions tests/test_filesink_rotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,14 @@ def creation_time(filepath):
assert tmpdir.join("test.2018-01-01_00-00-00_000000.log").check(exists=1)


@pytest.mark.parametrize(
"rotation", [object(), os, datetime.date(2017, 11, 11), datetime.datetime.now(), 1j]
)
def test_invalid_rotation(rotation):
with pytest.raises(TypeError):
logger.add("test.log", rotation=rotation)


@pytest.mark.parametrize(
"rotation",
[
Expand All @@ -475,13 +483,8 @@ def creation_time(filepath):
"foobar",
"w5 at [not|a|time]",
"[not|a|day] at 12:00",
object(),
os,
datetime.date(2017, 11, 11),
datetime.datetime.now(),
1j,
],
)
def test_invalid_rotation(rotation):
def test_unknown_rotation(rotation):
with pytest.raises(ValueError):
logger.add("test.log", rotation=rotation)
40 changes: 31 additions & 9 deletions tests/test_levels.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,37 +180,59 @@ def foobar(_, message, *args, **kwargs):
assert writer.read() == parse("<blue>foobar 33 🤖 Logged message</blue>\n")


@pytest.mark.parametrize("level", ["foo", -1, 3.4, object()])
@pytest.mark.parametrize("level", [3.4, object()])
def test_log_invalid_level(writer, level):
logger.add(writer)
with pytest.raises(TypeError):
logger.log(level, "test")


@pytest.mark.parametrize("level", ["foo", "debug", -1])
def test_log_unknown_level(writer, level):
logger.add(writer)
with pytest.raises(ValueError):
logger.log(level, "test")


@pytest.mark.parametrize("level_name", [10, object()])
def test_add_invalid_level_name(level_name):
with pytest.raises(ValueError):
with pytest.raises(TypeError):
logger.level(level_name, 11)


@pytest.mark.parametrize("level_value", ["1", -1, 3.4, object()])
def test_add_invalid_level_value(level_value):
with pytest.raises(ValueError):
@pytest.mark.parametrize("level_value", ["1", object(), 3.4])
def test_add_invalid_level_type(level_value):
with pytest.raises(TypeError):
logger.level("test", level_value)


@pytest.mark.parametrize("level", ["foo", 10, object()])
def test_get_invalid_level(level):
def test_add_invalid_level_value():
with pytest.raises(ValueError):
logger.level("test", -1)


@pytest.mark.parametrize("level", [10, object()])
def test_get_invalid_level(level):
with pytest.raises(TypeError):
logger.level(level)


@pytest.mark.parametrize("level", ["foo", 10, object()])
def test_edit_invalid_level(level):
def test_get_unknown_level():
with pytest.raises(ValueError):
logger.level("foo")


@pytest.mark.parametrize("level", [10, object()])
def test_edit_invalid_level(level):
with pytest.raises(TypeError):
logger.level(level, icon="?")


def test_edit_unknown_level():
with pytest.raises(ValueError):
logger.level("foo", icon="?")


@pytest.mark.parametrize("color", ["<foo>", "</red>"])
def test_add_invalid_level_color(color):
with pytest.raises(ValueError):
Expand Down
6 changes: 3 additions & 3 deletions tests/test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,17 +128,17 @@ def test_cast_with_irrelevant_value(tmpdir):

@pytest.mark.parametrize("file", [object(), 123, dict])
def test_invalid_file(file):
with pytest.raises(ValueError):
with pytest.raises(TypeError):
next(logger.parse(file, r"pattern"))


@pytest.mark.parametrize("pattern", [object(), 123, dict])
def test_invalid_pattern(fileobj, pattern):
with pytest.raises(ValueError):
with pytest.raises(TypeError):
next(logger.parse(fileobj, pattern))


@pytest.mark.parametrize("cast", [object(), 123])
def test_invalid_cast(fileobj, cast):
with pytest.raises(ValueError):
with pytest.raises(TypeError):
next(logger.parse(fileobj, r"pattern", cast=cast))
2 changes: 1 addition & 1 deletion tests/test_remove.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,5 @@ def test_invalid_handler_id_value(writer):

@pytest.mark.parametrize("handler_id", [sys.stderr, sys, object(), int])
def test_invalid_handler_id_type(handler_id):
with pytest.raises(ValueError, match=r"^Invalid handler id.*"):
with pytest.raises(TypeError, match=r"^Invalid handler id.*"):
logger.remove(handler_id)

0 comments on commit 361b448

Please sign in to comment.