1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
|
from __future__ import annotations
from importlib.metadata import version
import marshmallow
import pytest
import sqlalchemy as sa
from marshmallow import Schema, ValidationError, fields, validate
from pytest_lazy_fixtures import lf
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema, SQLAlchemySchema, auto_field
from marshmallow_sqlalchemy.exceptions import IncorrectSchemaTypeError
from marshmallow_sqlalchemy.fields import Related
# -----------------------------------------------------------------------------
@pytest.fixture
def teacher(models, session):
school = models.School(id=42, name="Univ. Of Whales")
teacher_ = models.Teacher(
id=24, full_name="Teachy McTeachFace", current_school=school
)
session.add(teacher_)
session.flush()
return teacher_
@pytest.fixture
def school(models, session):
school = models.School(id=42, name="Univ. Of Whales")
students = [
models.Student(id=35, full_name="Bob Smith", current_school=school),
models.Student(id=53, full_name="John Johnson", current_school=school),
]
session.add_all(students)
session.flush()
return school
class EntityMixin:
id = auto_field(dump_only=True)
# Auto schemas with default options
@pytest.fixture
def sqla_auto_model_schema(models, request) -> SQLAlchemyAutoSchema:
class TeacherSchema(SQLAlchemyAutoSchema[models.Teacher]):
class Meta:
model = models.Teacher
full_name = auto_field(validate=validate.Length(max=20))
return TeacherSchema()
@pytest.fixture
def sqla_auto_table_schema(models, request) -> SQLAlchemyAutoSchema:
class TeacherSchema(SQLAlchemyAutoSchema):
class Meta:
table = models.Teacher.__table__
full_name = auto_field(validate=validate.Length(max=20))
return TeacherSchema()
# Schemas with relationships
@pytest.fixture
def sqla_schema_with_relationships(models, request) -> SQLAlchemySchema:
class TeacherSchema(EntityMixin, SQLAlchemySchema[models.Teacher]):
class Meta:
model = models.Teacher
full_name = auto_field(validate=validate.Length(max=20))
current_school = auto_field()
substitute = auto_field()
data = auto_field()
return TeacherSchema()
@pytest.fixture
def sqla_auto_model_schema_with_relationships(models, request) -> SQLAlchemyAutoSchema:
class TeacherSchema(SQLAlchemyAutoSchema[models.Teacher]):
class Meta:
model = models.Teacher
include_relationships = True
full_name = auto_field(validate=validate.Length(max=20))
return TeacherSchema()
# Schemas with foreign keys
@pytest.fixture
def sqla_schema_with_fks(models, request) -> SQLAlchemySchema:
class TeacherSchema(EntityMixin, SQLAlchemySchema[models.Teacher]):
class Meta:
model = models.Teacher
full_name = auto_field(validate=validate.Length(max=20))
current_school_id = auto_field()
data = auto_field()
return TeacherSchema()
@pytest.fixture
def sqla_auto_model_schema_with_fks(models, request) -> SQLAlchemyAutoSchema:
class TeacherSchema(SQLAlchemyAutoSchema[models.Teacher]):
class Meta:
model = models.Teacher
include_fk = True
include_relationships = False
full_name = auto_field(validate=validate.Length(max=20))
return TeacherSchema()
# -----------------------------------------------------------------------------
@pytest.mark.parametrize(
"schema",
(
lf("sqla_schema_with_relationships"),
lf("sqla_auto_model_schema_with_relationships"),
),
)
def test_dump_with_relationships(teacher, schema):
assert schema.dump(teacher) == {
"id": teacher.id,
"full_name": teacher.full_name,
"current_school": 42,
"substitute": None,
"data": None,
}
@pytest.mark.parametrize(
"schema",
(
lf("sqla_schema_with_fks"),
lf("sqla_auto_model_schema_with_fks"),
),
)
def test_dump_with_foreign_keys(teacher, schema):
assert schema.dump(teacher) == {
"id": teacher.id,
"full_name": teacher.full_name,
"current_school_id": 42,
"data": None,
}
def test_table_schema_dump(teacher, sqla_auto_table_schema):
assert sqla_auto_table_schema.dump(teacher) == {
"id": teacher.id,
"full_name": teacher.full_name,
"data": None,
}
@pytest.mark.parametrize(
"schema",
(
lf("sqla_schema_with_relationships"),
lf("sqla_schema_with_fks"),
lf("sqla_auto_model_schema"),
lf("sqla_auto_table_schema"),
),
)
def test_load(schema):
assert schema.load({"full_name": "Teachy T"}) == {"full_name": "Teachy T"}
class TestLoadInstancePerSchemaInstance:
@pytest.fixture
def schema_no_load_instance(self, models, session):
class TeacherSchema(SQLAlchemySchema[models.Teacher]): # type: ignore[name-defined]
class Meta:
model = models.Teacher
sqla_session = session
# load_instance = False is the default
full_name = auto_field(validate=validate.Length(max=20))
current_school = auto_field()
substitute = auto_field()
return TeacherSchema
@pytest.fixture
def schema_with_load_instance(self, schema_no_load_instance: type):
class TeacherSchema(schema_no_load_instance):
class Meta(schema_no_load_instance.Meta): # type: ignore[name-defined]
load_instance = True
return TeacherSchema
@pytest.fixture
def auto_schema_no_load_instance(self, models, session):
class TeacherSchema(SQLAlchemyAutoSchema[models.Teacher]): # type: ignore[name-defined]
class Meta:
model = models.Teacher
sqla_session = session
# load_instance = False is the default
return TeacherSchema
@pytest.fixture
def auto_schema_with_load_instance(self, auto_schema_no_load_instance: type):
class TeacherSchema(auto_schema_no_load_instance):
class Meta(auto_schema_no_load_instance.Meta): # type: ignore[name-defined]
load_instance = True
return TeacherSchema
@pytest.mark.parametrize(
"Schema",
(
lf("schema_no_load_instance"),
lf("schema_with_load_instance"),
lf("auto_schema_no_load_instance"),
lf("auto_schema_with_load_instance"),
),
)
def test_toggle_load_instance_per_schema(self, models, Schema):
tname = "Teachy T"
source = {"full_name": tname}
# No per-instance override
load_instance_default = Schema()
result = load_instance_default.load(source)
default = load_instance_default.opts.load_instance
default_type = models.Teacher if default else dict
assert isinstance(result, default_type)
# Override the default
override = Schema(load_instance=not default)
result = override.load(source)
override_type = dict if default else models.Teacher
assert isinstance(result, override_type)
@pytest.mark.parametrize(
"schema",
(
lf("sqla_schema_with_relationships"),
lf("sqla_schema_with_fks"),
lf("sqla_auto_model_schema"),
lf("sqla_auto_table_schema"),
),
)
def test_load_validation_errors(schema):
with pytest.raises(ValidationError):
schema.load({"full_name": "x" * 21})
def test_auto_field_on_plain_schema_raises_error():
class BadSchema(Schema):
name = auto_field()
with pytest.raises(IncorrectSchemaTypeError):
BadSchema()
def test_cannot_set_both_model_and_table(models):
with pytest.raises(ValueError, match="Cannot set both"):
class BadWidgetSchema(SQLAlchemySchema):
class Meta:
model = models.Teacher
table = models.Teacher
def test_passing_model_to_auto_field(models, teacher):
class TeacherSchema(SQLAlchemySchema):
current_school_id = auto_field(model=models.Teacher)
schema = TeacherSchema()
assert schema.dump(teacher) == {"current_school_id": teacher.current_school_id}
def test_passing_table_to_auto_field(models, teacher):
class TeacherSchema(SQLAlchemySchema):
current_school_id = auto_field(table=models.Teacher.__table__)
schema = TeacherSchema()
assert schema.dump(teacher) == {"current_school_id": teacher.current_school_id}
# https://github.com/marshmallow-code/marshmallow-sqlalchemy/issues/190
def test_auto_schema_skips_synonyms(models):
class TeacherSchema(SQLAlchemyAutoSchema[models.Teacher]): # type: ignore[name-defined]
class Meta:
model = models.Teacher
include_fk = True
schema = TeacherSchema()
assert "current_school_id" in schema.fields
assert "curr_school_id" not in schema.fields
def test_auto_field_works_with_synonym(models):
class TeacherSchema(SQLAlchemyAutoSchema):
class Meta:
model = models.Teacher
include_fk = True
curr_school_id = auto_field()
schema = TeacherSchema()
assert "current_school_id" in schema.fields
assert "curr_school_id" in schema.fields
# Regresion test https://github.com/marshmallow-code/marshmallow-sqlalchemy/issues/306
def test_auto_field_works_with_ordered_flag(models):
class StudentSchema(SQLAlchemyAutoSchema[models.Student]): # type: ignore[name-defined]
class Meta:
model = models.Student
ordered = True
full_name = auto_field()
schema = StudentSchema()
# Declared fields precede auto-generated fields
assert tuple(schema.fields.keys()) == (
"full_name",
"course_count",
"id",
"dob",
"date_created",
)
class TestAliasing:
@pytest.fixture
def aliased_schema(self, models):
class TeacherSchema(SQLAlchemySchema):
class Meta:
model = models.Teacher
# Generate field from "full_name", pull from "full_name" attribute, output to "name"
name = auto_field("full_name")
return TeacherSchema()
@pytest.fixture
def aliased_auto_schema(self, models):
class TeacherSchema(SQLAlchemyAutoSchema):
class Meta:
model = models.Teacher
exclude = ("full_name",)
# Generate field from "full_name", pull from "full_name" attribute, output to "name"
name = auto_field("full_name")
return TeacherSchema()
@pytest.fixture
def aliased_attribute_schema(self, models):
class TeacherSchema(SQLAlchemySchema):
class Meta:
model = models.Teacher
# Generate field from "full_name", pull from "fname" attribute, output to "name"
name = auto_field("full_name", attribute="fname")
return TeacherSchema()
@pytest.mark.parametrize(
"schema",
(
lf("aliased_schema"),
lf("aliased_auto_schema"),
),
)
def test_passing_column_name(self, schema, teacher):
assert schema.fields["name"].attribute == "full_name"
dumped = schema.dump(teacher)
assert dumped["name"] == teacher.full_name
def test_passing_column_name_and_attribute(self, teacher, aliased_attribute_schema):
assert aliased_attribute_schema.fields["name"].attribute == "fname"
dumped = aliased_attribute_schema.dump(teacher)
assert dumped["name"] == teacher.fname
class TestModelInstanceDeserialization:
@pytest.fixture
def sqla_schema_class(self, models, session):
class TeacherSchema(SQLAlchemySchema):
class Meta:
model = models.Teacher
load_instance = True
sqla_session = session
full_name = auto_field(validate=validate.Length(max=20))
current_school = auto_field()
substitute = auto_field()
return TeacherSchema
@pytest.fixture
def sqla_auto_schema_class(self, models, session):
class TeacherSchema(SQLAlchemyAutoSchema):
class Meta:
model = models.Teacher
include_relationships = True
load_instance = True
sqla_session = session
return TeacherSchema
@pytest.mark.parametrize(
"SchemaClass",
(
lf("sqla_schema_class"),
lf("sqla_auto_schema_class"),
),
)
def test_load(self, teacher, SchemaClass, models):
schema = SchemaClass(unknown=marshmallow.INCLUDE)
dump_data = schema.dump(teacher)
load_data = schema.load(dump_data)
assert isinstance(load_data, models.Teacher)
def test_load_transient(self, models, teacher):
class TeacherSchema(SQLAlchemyAutoSchema):
class Meta:
model = models.Teacher
load_instance = True
transient = True
schema = TeacherSchema()
dump_data = schema.dump(teacher)
load_data = schema.load(dump_data)
assert isinstance(load_data, models.Teacher)
state = sa.inspect(load_data)
assert state.transient
def test_override_transient(self, models, teacher):
# marshmallow-code/marshmallow-sqlalchemy#388
class TeacherSchema(SQLAlchemyAutoSchema):
class Meta:
model = models.Teacher
load_instance = True
transient = True
schema = TeacherSchema(transient=False)
assert schema.transient is False
def test_related_when_model_attribute_name_distinct_from_column_name(
models,
session,
teacher,
):
class TeacherSchema(SQLAlchemyAutoSchema):
class Meta:
model = models.Teacher
load_instance = True
sqla_session = session
current_school = Related(["id", "name"])
dump_data = TeacherSchema().dump(teacher)
assert "school_id" not in dump_data["current_school"]
assert dump_data["current_school"]["id"] == teacher.current_school.id
assert dump_data["current_school"]["name"] == teacher.current_school.name
new_teacher = TeacherSchema().load(dump_data, transient=True)
assert new_teacher.current_school.id == teacher.current_school.id
assert TeacherSchema().load(dump_data) is teacher
# https://github.com/marshmallow-code/marshmallow-sqlalchemy/issues/338
def test_auto_field_works_with_assoc_proxy(models):
class StudentSchema(SQLAlchemySchema):
class Meta:
model = models.Student
possible_teachers = auto_field()
schema = StudentSchema()
assert "possible_teachers" in schema.fields
def test_dump_and_load_with_assoc_proxy_multiplicity(models, session, school):
class SchoolSchema(SQLAlchemySchema):
class Meta:
model = models.School
load_instance = True
sqla_session = session
student_ids = auto_field()
schema = SchoolSchema()
assert "student_ids" in schema.fields
dump_data = schema.dump(school)
assert "student_ids" in dump_data
assert dump_data["student_ids"] == list(school.student_ids)
new_school = schema.load(dump_data, transient=True)
assert list(new_school.student_ids) == list(school.student_ids)
def test_dump_and_load_with_assoc_proxy_multiplicity_dump_only_kwargs(
models, session, school
):
class SchoolSchema(SQLAlchemySchema):
class Meta:
model = models.School
load_instance = True
sqla_session = session
student_ids = auto_field(dump_only=True, data_key="student_identifiers")
schema = SchoolSchema()
assert "student_ids" in schema.fields
assert schema.fields["student_ids"] not in schema.load_fields.values()
assert schema.fields["student_ids"] in schema.dump_fields.values()
dump_data = schema.dump(school)
assert "student_ids" not in dump_data
assert "student_identifiers" in dump_data
assert dump_data["student_identifiers"] == list(school.student_ids)
with pytest.raises(ValidationError):
schema.load(dump_data, transient=True)
def test_dump_and_load_with_assoc_proxy_multiplicity_load_only_only_kwargs(
models, session, school
):
class SchoolSchema(SQLAlchemySchema):
class Meta:
model = models.School
load_instance = True
sqla_session = session
student_ids = auto_field(load_only=True, data_key="student_identifiers")
schema = SchoolSchema()
assert "student_ids" in schema.fields
assert schema.fields["student_ids"] not in schema.dump_fields.values()
assert schema.fields["student_ids"] in schema.load_fields.values()
dump_data = schema.dump(school)
assert "student_identifers" not in dump_data
new_school = schema.load(
{"student_identifiers": list(school.student_ids)}, transient=True
)
assert list(new_school.student_ids) == list(school.student_ids)
# https://github.com/marshmallow-code/marshmallow-sqlalchemy/issues/440
def test_auto_schema_with_model_allows_subclasses_to_override_include_fk(models):
class TeacherSchema(SQLAlchemyAutoSchema):
inherited_field = fields.String()
class Meta:
model = models.Teacher
include_fk = True
schema = TeacherSchema()
assert "current_school_id" in schema.fields
class TeacherNoFkSchema(TeacherSchema):
class Meta(TeacherSchema.Meta):
include_fk = False
schema2 = TeacherNoFkSchema()
assert "id" in schema2.fields
assert "inherited_field" in schema2.fields
assert "current_school_id" not in schema2.fields
def test_auto_schema_with_model_allows_subclasses_to_override_exclude(models):
class TeacherSchema(SQLAlchemyAutoSchema):
inherited_field = fields.String()
class Meta:
model = models.Teacher
include_fk = True
schema = TeacherSchema()
assert "current_school_id" in schema.fields
class TeacherNoFkSchema(TeacherSchema):
class Meta(TeacherSchema.Meta):
exclude = ("current_school_id",)
schema2 = TeacherNoFkSchema()
assert "id" in schema2.fields
assert "inherited_field" in schema2.fields
assert "current_school_id" not in schema2.fields
def test_auto_schema_with_model_allows_subclasses_to_override_include_fk_with_explicit_field(
models,
):
class TeacherSchema(SQLAlchemyAutoSchema):
inherited_field = fields.String()
class Meta:
model = models.Teacher
include_fk = True
schema = TeacherSchema()
assert "current_school_id" in schema.fields
class TeacherNoFkSchema(TeacherSchema):
current_school_id = fields.Integer()
class Meta(TeacherSchema.Meta):
include_fk = False
schema2 = TeacherNoFkSchema()
assert "id" in schema2.fields
assert "inherited_field" in schema2.fields
assert "current_school_id" in schema2.fields
def test_auto_schema_with_table_allows_subclasses_to_override_include_fk(models):
class TeacherSchema(SQLAlchemyAutoSchema):
inherited_field = fields.Integer()
class Meta:
table = models.Teacher.__table__
include_fk = True
schema = TeacherSchema()
assert "current_school_id" in schema.fields
class TeacherNoFkSchema(TeacherSchema):
class Meta(TeacherSchema.Meta):
include_fk = False
schema2 = TeacherNoFkSchema()
assert "id" in schema2.fields
assert "inherited_field" in schema2.fields
assert "current_school_id" not in schema2.fields
def test_auto_schema_with_table_allows_subclasses_to_override_include_fk_with_explicit_field(
models,
):
class TeacherSchema(SQLAlchemyAutoSchema):
inherited_field = fields.Integer()
class Meta:
table = models.Teacher.__table__
include_fk = True
schema = TeacherSchema()
assert "current_school_id" in schema.fields
class TeacherNoFkModelSchema(TeacherSchema):
current_school_id = fields.Integer()
class Meta(TeacherSchema.Meta):
include_fk = False
schema2 = TeacherNoFkModelSchema()
assert "id" in schema2.fields
assert "inherited_field" in schema2.fields
assert "current_school_id" in schema2.fields
def test_auto_schema_with_model_can_inherit_declared_field_for_foreign_key_column_when_include_fk_is_false(
models,
):
class BaseTeacherSchema(Schema):
current_school_id = fields.Integer()
class TeacherSchema(BaseTeacherSchema, SQLAlchemyAutoSchema):
class Meta:
model = models.Teacher
include_fk = False
schema = TeacherSchema()
assert "current_school_id" in schema.fields
def test_auto_schema_with_table_can_inherit_declared_field_for_foreign_key_column_when_include_fk_is_false(
models,
):
class BaseTeacherSchema(Schema):
current_school_id = fields.Integer()
class TeacherSchema(BaseTeacherSchema, SQLAlchemyAutoSchema):
class Meta:
table = models.Teacher.__table__
include_fk = False
schema = TeacherSchema()
assert "current_school_id" in schema.fields
def test_auto_field_does_not_accept_arbitrary_kwargs(models):
if int(version("marshmallow")[0]) < 4:
from marshmallow.warnings import RemovedInMarshmallow4Warning
with pytest.warns(
RemovedInMarshmallow4Warning,
match="Passing field metadata as keyword arguments is deprecated",
):
class CourseSchema(SQLAlchemyAutoSchema):
class Meta:
model = models.Course
name = auto_field(description="A course name")
else:
with pytest.raises(TypeError, match="unexpected keyword argument"):
class CourseSchema(SQLAlchemyAutoSchema): # type: ignore[no-redef]
class Meta:
model = models.Course
name = auto_field(description="A course name")
# https://github.com/marshmallow-code/marshmallow-sqlalchemy/issues/394
def test_dumping_pickle_field(models, teacher):
class TeacherSchema(SQLAlchemySchema):
class Meta:
model = models.Teacher
data = auto_field()
teacher.data = {"foo": "bar"}
schema = TeacherSchema()
assert schema.dump(teacher) == {
"data": {"foo": "bar"},
}
|