Skip to content

Commit 431fa9f

Browse files
WilliamBergaminClaude
andauthored
perf(models): cache validator names per class (#2036)
Co-authored-by: Claude <svc-devxp-claude@slack-corp.com>
1 parent e0eac68 commit 431fa9f

2 files changed

Lines changed: 61 additions & 6 deletions

File tree

‎slack_sdk/models/basic_objects.py‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from abc import ABCMeta, abstractmethod
2-
from functools import wraps
3-
from typing import Callable, Iterable, Set, Union, Any
2+
from functools import lru_cache, wraps
3+
from typing import Callable, FrozenSet, Iterable, Set, Union, Any
44

55
from slack_sdk.errors import SlackObjectFormationError
66

@@ -21,6 +21,15 @@ def __str__(self):
2121
]
2222

2323

24+
def _is_validator(value: Any) -> bool:
25+
return callable(value) and hasattr(value, "validator")
26+
27+
28+
@lru_cache(maxsize=None)
29+
def _class_validator_names(cls: type) -> FrozenSet[str]:
30+
return frozenset(name for name in dir(cls) if not name.startswith("__") and _is_validator(getattr(cls, name, None)))
31+
32+
2433
class JsonObject(BaseObject, metaclass=ABCMeta):
2534
"""The base class for JSON serializable class objects."""
2635

@@ -36,10 +45,12 @@ def validate_json(self) -> None:
3645
Raises:
3746
SlackObjectFormationError: if the object was not valid
3847
"""
39-
for attribute in (func for func in dir(self) if not func.startswith("__")):
40-
method = getattr(self, attribute, None)
41-
if callable(method) and hasattr(method, "validator"):
42-
method()
48+
instance_attribute_names = (name for name in vars(self) if not name.startswith("__"))
49+
candidate_names = _class_validator_names(type(self)).union(instance_attribute_names)
50+
for name in sorted(candidate_names):
51+
attribute: Any = getattr(self, name, None)
52+
if _is_validator(attribute):
53+
attribute()
4354

4455
def get_object_attribute(self, key: str):
4556
return getattr(self, key, None)

‎tests/slack_sdk/models/test_objects.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,26 @@ def always_valid_test(self):
2828
return True
2929

3030

31+
class MultipleFailingValidatorsObject(JsonObject):
32+
attributes = {"some"}
33+
34+
def __init__(self):
35+
self.some = "value"
36+
37+
@JsonValidator("b_check failed")
38+
def b_check(self):
39+
return False
40+
41+
@JsonValidator("a_check failed")
42+
def a_check(self):
43+
return False
44+
45+
46+
class OverriddenValidatorObject(SimpleJsonObject):
47+
def test_valid(self):
48+
return False
49+
50+
3151
class KeyValueObject(JsonObject):
3252
attributes = {"name", "value"}
3353

@@ -143,6 +163,30 @@ def test_eq(self):
143163

144164
self.assertNotEqual(self.good_test_object, None)
145165

166+
def test_validators_run_in_alphabetical_order(self):
167+
obj = MultipleFailingValidatorsObject()
168+
for _ in range(2):
169+
with self.assertRaisesRegex(SlackObjectFormationError, "a_check failed"):
170+
obj.to_dict()
171+
172+
def test_validator_overridden_by_plain_method_is_skipped(self):
173+
obj = OverriddenValidatorObject()
174+
obj.test = STRING_51_CHARS
175+
self.assertDictEqual(obj.to_dict(), {"some": "this is", "test": STRING_51_CHARS, "keys": "object"})
176+
177+
def test_validator_shadowed_by_instance_attribute_is_skipped(self):
178+
self.bad_test_object.test_valid = "shadowed"
179+
self.assertDictEqual(
180+
self.bad_test_object.to_dict(),
181+
{"some": "this is", "test": STRING_51_CHARS, "keys": "object"},
182+
)
183+
184+
def test_validator_set_on_instance_runs(self):
185+
obj = SimpleJsonObject()
186+
obj.instance_check = JsonValidator("instance_check failed")(lambda: False)
187+
with self.assertRaisesRegex(SlackObjectFormationError, "instance_check failed"):
188+
obj.to_dict()
189+
146190

147191
class JsonValidatorTests(unittest.TestCase):
148192
def setUp(self) -> None:

0 commit comments

Comments
 (0)