Skip to content

Commit ea58d97

Browse files
committed
Expose default values in the Thing Description
This will fail if the default won't validate. We probably want a check for this when the `Thing` is defined, as otherwise we will get annoying and unclear errors after the server has started.
1 parent 2bf597e commit ea58d97

2 files changed

Lines changed: 17 additions & 1 deletion

File tree

src/labthings_fastapi/properties.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@ def get_property() -> Any:
473473
return self.__get__(thing)
474474

475475
def property_affordance(
476-
self, thing: Thing, path: str | None = None
476+
self, thing: Owner, path: str | None = None
477477
) -> PropertyAffordance:
478478
"""Represent the property in a Thing Description.
479479
@@ -500,12 +500,22 @@ def property_affordance(
500500
),
501501
]
502502
data_schema: DataSchema = type_to_dataschema(self.model)
503+
extra_fields = {}
504+
try:
505+
# Try to get hold of the default - may raise FeatureNotAvailable
506+
default = self.default(thing)
507+
# Validate and dump it with the model to ensure it's simple types only
508+
default_validated = self.model.model_validate(default)
509+
extra_fields["default"] = default_validated.model_dump()
510+
except FeatureNotAvailable:
511+
pass # Default should only be included if it's needed.
503512
pa: PropertyAffordance = PropertyAffordance(
504513
title=self.title,
505514
forms=forms,
506515
description=self.description,
507516
readOnly=self.readonly,
508517
writeOnly=False, # write-only properties are not yet supported
518+
**extra_fields,
509519
)
510520
# We merge the data schema with the property affordance (which subclasses the
511521
# DataSchema model) with the affordance second so its values take priority.

tests/test_property.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,3 +504,9 @@ def strprop(self) -> str:
504504
# Resetting won't work for FunctionalProperty
505505
with pytest.raises(FeatureNotAvailable):
506506
example.properties["strprop"].reset()
507+
508+
# Check defaults show up in the Thing Description
509+
td = example.thing_description_dict()
510+
assert td["properties"]["intprop"]["default"] == 42
511+
assert td["properties"]["listprop"]["default"] == ["a", "list"]
512+
assert "default" not in td["properties"]["strprop"]

0 commit comments

Comments
 (0)