Skip to content

Commit

Permalink
Fix incorrect default handling for Attributes.
Browse files Browse the repository at this point in the history
Fixes #318
  • Loading branch information
ctheune authored and elikoga committed Nov 29, 2023
1 parent 2fa09cf commit 177584b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
7 changes: 6 additions & 1 deletion src/batou/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -1045,6 +1045,9 @@ class ConfigString(str):
"""


NO_DEFAULT = object()


class Attribute(object):
"""An attribute descriptor is used to provide:
Expand Down Expand Up @@ -1084,7 +1087,7 @@ class Attribute(object):
def __init__(
self,
conversion=str,
default=None,
default=NO_DEFAULT,
expand=True,
map=False,
):
Expand All @@ -1105,6 +1108,8 @@ def __get__(self, obj, objtype=None):
value = self.default
if isinstance(self.default, ConfigString):
value = self.from_config_string(obj, value)
elif value is NO_DEFAULT:
raise AttributeError("No override and no default given.")
self.__set__(obj, value)
return self.instances[obj]

Expand Down
16 changes: 14 additions & 2 deletions src/batou/tests/test_component.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,10 +577,23 @@ class Foo(Component):

f = Foo()
root.component += f
root.prepare()
assert f.a == expected


def test_attribute_missing_override_and_default(root):
class Foo(Component):
a = Attribute(str)

def configure(self):
self.a

f = Foo()
with pytest.raises(AttributeError) as e:
root.component += f

assert e.value.args[0] == "No override and no default given."


@pytest.mark.parametrize(
"default,expected",
[
Expand All @@ -597,7 +610,6 @@ class Foo(Component):

f = Foo()
root.component += f
root.prepare()
assert f.a == expected


Expand Down

0 comments on commit 177584b

Please sign in to comment.