Skip to content

Commit

Permalink
Test attrs helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
znichollscr committed Feb 5, 2024
1 parent 36a522a commit e0a1958
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 9 deletions.
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,8 @@ docstring-code-format = true
"test*.py" = [
"D", # Documentation not needed in tests
"S101", # S101 Use of `assert` detected
"PLR2004" # Magic value used in comparison
"PLR2004", # Magic value used in comparison
"TRY003", # Test code, it's fine
]
"docs/source/notebooks/*" = [
"D100", # Missing docstring at the top of file
Expand Down
43 changes: 35 additions & 8 deletions src/pydoit_nb/attrs_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,40 @@
T = TypeVar("T")


class AttributeInitialisationError(ValueError):
"""
Raised when there is an issue while initialising an :obj:`attr.Attribute`
"""

def __init__(
self,
instance: Any,
attribute: attr.Attribute[Any],
value: T,
) -> None:
"""
Initialise the error
Parameters
----------
instance
Instance being initialised
attribute
Attribute being set
value
Value being used to set the attribute
"""
error_msg = (
"Error raised while initialising attribute "
f"``{attribute.name}`` of ``{type(instance)}``. "
f"Value provided: {value}"
)

super().__init__(error_msg)


def add_attrs_context(
original: Callable[[Any, attr.Attribute[Any], T], None],
) -> Callable[[Any, attr.Attribute[Any], T], None]:
Expand Down Expand Up @@ -50,14 +84,7 @@ def with_attrs_context(
try:
original(instance, attribute, value)
except Exception as exc:
if hasattr(exc, "add_note"):
exc.add_note(
"\nError raised while initialising attribute "
f"``{attribute.name}`` of ``{type(instance)}``. "
f"\nValue provided: {value}"
)

raise
raise AttributeInitialisationError(instance=instance, attribute=attribute, value=value) from exc

return with_attrs_context

Expand Down
35 changes: 35 additions & 0 deletions tests/unit/test_attrs_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""
Test attrs_helpers module
"""
import re
from unittest.mock import Mock

import pytest

from pydoit_nb.attrs_helpers import AttributeInitialisationError, make_attrs_validator_compatible_single_input


def test_make_attrs_validator_compatible_single_input():
def func(inp: str) -> None:
if inp != "hi":
raise ValueError(f"inp must be hi, received: {inp}")

wrapped = make_attrs_validator_compatible_single_input(func)

instance = Mock()
attribute = Mock()
attribute.name = "attribute_name"
# No error
wrapped(instance, attribute, "hi")

# Error
error_msg = re.escape(
"Error raised while initialising attribute "
f"``attribute_name`` of ``{type(instance)}``. "
"Value provided: bye"
)
with pytest.raises(AttributeInitialisationError, match=error_msg) as exc:
wrapped(instance, attribute, "bye")

assert isinstance(exc.value.__cause__, ValueError)
assert str(exc.value.__cause__) == "inp must be hi, received: bye"

0 comments on commit e0a1958

Please sign in to comment.