Skip to content

Commit

Permalink
Use TypeError instead of ValueError where appropriate.
Browse files Browse the repository at this point in the history
  • Loading branch information
pelme committed Sep 14, 2024
1 parent b7b0b15 commit 408f70f
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 13 deletions.
2 changes: 2 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
## next
- Raise errors directly on invalid children. This avoids cryptic stack traces.
[PR #56](https://github.com/pelme/htpy/pull/56).
- Raise TypeError rather than ValueError when invalid types are passed as
attributes or children. [PR #59].

## 24.9.1 - 2024-09-09
- Raise errors directly on invalid attributes. This avoids cryptic stack traces
Expand Down
10 changes: 5 additions & 5 deletions htpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def _class_names_for_items(items: t.Any) -> t.Any:

def _id_class_names_from_css_str(x: t.Any) -> dict[str, Attribute]:
if not isinstance(x, str):
raise ValueError(f"id/class strings must be str. got {x}")
raise TypeError(f"id/class strings must be str. got {x}")

if "#" in x and "." in x and x.find("#") > x.find("."):
raise ValueError("id (#) must be specified before classes (.)")
Expand Down Expand Up @@ -85,7 +85,7 @@ def _kwarg_attribute_name(name: str) -> str:
def _generate_attrs(raw_attrs: dict[str, Attribute]) -> Iterable[tuple[str, Attribute]]:
for key, value in raw_attrs.items():
if not isinstance(key, str): # pyright: ignore [reportUnnecessaryIsInstance]
raise ValueError("Attribute key must be a string")
raise TypeError("Attribute key must be a string")

if value is False or value is None:
continue
Expand All @@ -99,7 +99,7 @@ def _generate_attrs(raw_attrs: dict[str, Attribute]) -> Iterable[tuple[str, Attr

else:
if not isinstance(value, str | int | _HasHtml):
raise ValueError(f"Attribute value must be a string or an integer , got {value!r}")
raise TypeError(f"Attribute value must be a string or an integer , got {value!r}")

yield _force_escape(key), _force_escape(value)

Expand Down Expand Up @@ -197,7 +197,7 @@ def _iter_node_context(x: Node, context_dict: dict[Context[t.Any], t.Any]) -> It
for child in x:
yield from _iter_node_context(child, context_dict)
else:
raise ValueError(f"{x!r} is not a valid child element")
raise TypeError(f"{x!r} is not a valid child element")


@functools.lru_cache(maxsize=300)
Expand Down Expand Up @@ -300,7 +300,7 @@ def _validate_children(children: t.Any) -> None:
_validate_children(child)
return

raise ValueError(f"{children!r} is not a valid child element")
raise TypeError(f"{children!r} is not a valid child element")


class Element(BaseElement):
Expand Down
8 changes: 4 additions & 4 deletions tests/test_attributes.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def test_id_class_bad_format() -> None:


def test_id_class_bad_type() -> None:
with pytest.raises(ValueError, match="id/class strings must be str. got {'oops': 'yes'}"):
with pytest.raises(TypeError, match="id/class strings must be str. got {'oops': 'yes'}"):
div({"oops": "yes"}, {}) # type: ignore


Expand Down Expand Up @@ -188,14 +188,14 @@ def test_attribute_priority() -> None:

@pytest.mark.parametrize("not_an_attr", [1234, b"foo", object(), object, 1, 0, None])
def test_invalid_attribute_key(not_an_attr: t.Any) -> None:
with pytest.raises(ValueError, match="Attribute key must be a string"):
str(div({not_an_attr: "foo"}))
with pytest.raises(TypeError, match="Attribute key must be a string"):
div({not_an_attr: "foo"})


@pytest.mark.parametrize(
"not_an_attr",
[12.34, b"foo", object(), object],
)
def test_invalid_attribute_value(not_an_attr: t.Any) -> None:
with pytest.raises(ValueError, match="Attribute value must be a string"):
with pytest.raises(TypeError, match="Attribute value must be a string"):
div(foo=not_an_attr)
8 changes: 4 additions & 4 deletions tests/test_children.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,13 +240,13 @@ class SomeClass:

@pytest.mark.parametrize("not_a_child", _invalid_children)
def test_invalid_child_direct(not_a_child: t.Any) -> None:
with pytest.raises(ValueError, match="is not a valid child element"):
with pytest.raises(TypeError, match="is not a valid child element"):
div[not_a_child]


@pytest.mark.parametrize("not_a_child", _invalid_children)
def test_invalid_child_nested_iterable(not_a_child: t.Any) -> None:
with pytest.raises(ValueError, match="is not a valid child element"):
with pytest.raises(TypeError, match="is not a valid child element"):
div[[not_a_child]]


Expand All @@ -256,7 +256,7 @@ def test_invalid_child_lazy_callable(not_a_child: t.Any) -> None:
Ensure proper exception is raised for lazily evaluated invalid children.
"""
element = div[lambda: not_a_child]
with pytest.raises(ValueError, match="is not a valid child element"):
with pytest.raises(TypeError, match="is not a valid child element"):
str(element)


Expand All @@ -270,5 +270,5 @@ def gen() -> t.Any:
yield not_a_child

element = div[gen()]
with pytest.raises(ValueError, match="is not a valid child element"):
with pytest.raises(TypeError, match="is not a valid child element"):
str(element)

0 comments on commit 408f70f

Please sign in to comment.