|
1 | | -from .models import DATE, DATETIME, MONEY, TIME, FlatModel |
| 1 | +import sqlalchemy as sa |
| 2 | + |
| 3 | +from .models import DATE, DATETIME, MONEY, TIME, Base, FlatModel, SerializerMixin |
2 | 4 |
|
3 | 5 |
|
4 | 6 | def test_no_defaults_no_rules(get_instance): |
@@ -345,3 +347,66 @@ def test_rules_for_nested_dicts_and_lists(get_instance): |
345 | 347 |
|
346 | 348 | assert "prop" in data |
347 | 349 | assert data["prop"] == i.prop |
| 350 | + |
| 351 | + |
| 352 | +def test_method_with_default_argument(): |
| 353 | + """Test that methods with default arguments are serialized""" |
| 354 | + |
| 355 | + class ModelWithDefaultMethod(Base, SerializerMixin): |
| 356 | + __tablename__ = "model_with_default_method" |
| 357 | + serialize_only = () |
| 358 | + serialize_rules = () |
| 359 | + |
| 360 | + id = sa.Column(sa.Integer, primary_key=True) |
| 361 | + string = sa.Column(sa.String(256), default="test") |
| 362 | + |
| 363 | + def is_liked(self, user=None): |
| 364 | + return user is not None |
| 365 | + |
| 366 | + i = ModelWithDefaultMethod(id=1, string="test") |
| 367 | + data = i.to_dict(rules=("is_liked",)) |
| 368 | + |
| 369 | + assert "is_liked" in data |
| 370 | + assert data["is_liked"] is False # Called without args, user=None |
| 371 | + |
| 372 | + |
| 373 | +def test_method_with_multiple_defaults(): |
| 374 | + """Test method with multiple default arguments""" |
| 375 | + |
| 376 | + class ModelWithMultiDefaults(Base, SerializerMixin): |
| 377 | + __tablename__ = "model_with_multi_defaults" |
| 378 | + serialize_only = () |
| 379 | + serialize_rules = () |
| 380 | + |
| 381 | + id = sa.Column(sa.Integer, primary_key=True) |
| 382 | + string = sa.Column(sa.String(256), default="test") |
| 383 | + |
| 384 | + def compute(self, a=1, b=2): |
| 385 | + return a + b |
| 386 | + |
| 387 | + i = ModelWithMultiDefaults(id=1, string="test") |
| 388 | + data = i.to_dict(rules=("compute",)) |
| 389 | + |
| 390 | + assert "compute" in data |
| 391 | + assert data["compute"] == 3 # 1 + 2 |
| 392 | + |
| 393 | + |
| 394 | +def test_method_with_required_arg_rejected(): |
| 395 | + """Test that methods with required args are still rejected""" |
| 396 | + |
| 397 | + class ModelWithRequiredArg(Base, SerializerMixin): |
| 398 | + __tablename__ = "model_with_required_arg" |
| 399 | + serialize_only = () |
| 400 | + serialize_rules = () |
| 401 | + |
| 402 | + id = sa.Column(sa.Integer, primary_key=True) |
| 403 | + string = sa.Column(sa.String(256), default="test") |
| 404 | + |
| 405 | + def method_required(self, user): # No default |
| 406 | + return user |
| 407 | + |
| 408 | + i = ModelWithRequiredArg(id=1, string="test") |
| 409 | + data = i.to_dict(rules=("method_required",)) |
| 410 | + |
| 411 | + # Should not be serialized (not callable without args) |
| 412 | + assert "method_required" not in data |
0 commit comments